def _check_compatible_regs(self, rhs):
        """Raise exception if the circuits are defined on incompatible registers"""
        list1 = self.qregs + self.cregs
        list2 = rhs.qregs + rhs.cregs
        for element1 in list1:
            for element2 in list2:
                if element2.name == element1.name:
                    if element1 != element2:
                        raise QiskitError("circuits are not compatible")

def
_check_compatible_regs
(
self
,
rhs
)
:
list1
=
self
.
qregs
+
self
.
cregs
list2
=
rhs
.
qregs
+
rhs
.
cregs
for
element1
in
list1
:
for
element2
in
list2
:
if
element2
.
name
==
element1
.
name
:
if
element1
!=
element2
:
raise
QiskitError
(
"circuits are not compatible"
)


def qasm(self):
        """Return OpenQASM string."""
        string_temp = self.header + "\n"
        string_temp += self.extension_lib + "\n"
        for register in self.qregs:
            string_temp += register.qasm() + "\n"
        for register in self.cregs:
            string_temp += register.qasm() + "\n"
        for instruction, qargs, cargs in self.data:
            if instruction.name == 'measure':
                qubit = qargs[0]
                clbit = cargs[0]
                string_temp += "%s %s[%d] -> %s[%d];\n" % (instruction.qasm(),
                                                           qubit[0].name, qubit[1],
                                                           clbit[0].name, clbit[1])
            else:
                string_temp += "%s %s;\n" % (instruction.qasm(),
                                             ",".join(["%s[%d]" % (j[0].name, j[1])
                                                       for j in qargs + cargs]))
        return string_temp

def
qasm
(
self
)
:
string_temp
=
self
.
header
+
"\n"
string_temp
+=
self
.
extension_lib
+
"\n"
for
register
in
self
.
qregs
:
string_temp
+=
register
.
qasm
(
)
+
"\n"
for
register
in
self
.
cregs
:
string_temp
+=
register
.
qasm
(
)
+
"\n"
for
instruction
,
qargs
,
cargs
in
self
.
data
:
if
instruction
.
name
==
'measure'
:
qubit
=
qargs
[
0
]
clbit
=
cargs
[
0
]
string_temp
+=
"%s %s[%d] -> %s[%d];\n"
%
(
instruction
.
qasm
(
)
,
qubit
[
0
]
.
name
,
qubit
[
1
]
,
clbit
[
0
]
.
name
,
clbit
[
1
]
)
else
:
string_temp
+=
"%s %s;\n"
%
(
instruction
.
qasm
(
)
,
","
.
join
(
[
"%s[%d]"
%
(
j
[
0
]
.
name
,
j
[
1
]
)
for
j
in
qargs
+
cargs
]
)
)
return
string_temp


def draw(self, scale=0.7, filename=None, style=None, output='text',
             interactive=False, line_length=None, plot_barriers=True,
             reverse_bits=False, justify=None):
        """Draw the quantum circuit

        Using the output parameter you can specify the format. The choices are:
        0. text: ASCII art string
        1. latex: high-quality images, but heavy external software dependencies
        2. matplotlib: purely in Python with no external dependencies

        Defaults to an overcomplete basis, in order to not alter gates.

        Args:
            scale (float): scale of image to draw (shrink if < 1)
            filename (str): file path to save image to
            style (dict or str): dictionary of style or file name of style
                file. You can refer to the
                :ref:`Style Dict Doc <style-dict-doc>` for more information
                on the contents.
            output (str): Select the output method to use for drawing the
                circuit. Valid choices are `text`, `latex`, `latex_source`,
                `mpl`.
            interactive (bool): when set true show the circuit in a new window
                (for `mpl` this depends on the matplotlib backend being used
                supporting this). Note when used with either the `text` or the
                `latex_source` output type this has no effect and will be
                silently ignored.
            line_length (int): sets the length of the lines generated by `text`
            reverse_bits (bool): When set to True reverse the bit order inside
                registers for the output visualization.
            plot_barriers (bool): Enable/disable drawing barriers in the output
                circuit. Defaults to True.
            justify (string): Options are `left`, `right` or `none`, if anything
                else is supplied it defaults to left justified. It refers to where
                gates should be placed in the output circuit if there is an option.
                `none` results in each gate being placed in its own column. Currently
                only supported by text drawer.

        Returns:
            PIL.Image or matplotlib.figure or str or TextDrawing:
                * PIL.Image: (output `latex`) an in-memory representation of the
                  image of the circuit diagram.
                * matplotlib.figure: (output `mpl`) a matplotlib figure object
                  for the circuit diagram.
                * str: (output `latex_source`). The LaTeX source code.
                * TextDrawing: (output `text`). A drawing that can be printed as
                  ascii art

        Raises:
            VisualizationError: when an invalid output method is selected
        """
        from qiskit.tools import visualization
        return visualization.circuit_drawer(self, scale=scale,
                                            filename=filename, style=style,
                                            output=output,
                                            interactive=interactive,
                                            line_length=line_length,
                                            plot_barriers=plot_barriers,
                                            reverse_bits=reverse_bits,
                                            justify=justify)

def draw ( self , scale = 0.7 , filename = None , style = None , output = 'text' , interactive = False , line_length = None , plot_barriers = True , reverse_bits = False , justify = None ) : from qiskit . tools import visualization return visualization . circuit_drawer ( self , scale = scale , filename = filename , style = style , output = output , interactive = interactive , line_length = line_length , plot_barriers = plot_barriers , reverse_bits = reverse_bits , justify = justify )


def size(self):
        """Returns total number of gate operations in circuit.

        Returns:
            int: Total number of gate operations.
        """
        gate_ops = 0
        for instr, _, _ in self.data:
            if instr.name not in ['barrier', 'snapshot']:
                gate_ops += 1
        return gate_ops

def size ( self ) : gate_ops = 0 for instr , _ , _ in self . data : if instr . name not in [ 'barrier' , 'snapshot' ] : gate_ops += 1 return gate_ops

Returns total number of gate operations in circuit .


def width(self):
        """Return number of qubits plus clbits in circuit.

        Returns:
            int: Width of circuit.

        """
        return sum(reg.size for reg in self.qregs+self.cregs)

def width ( self ) : return sum ( reg . size for reg in self . qregs + self . cregs )

Return number of qubits plus clbits in circuit .


def count_ops(self):
        """Count each operation kind in the circuit.

        Returns:
            dict: a breakdown of how many operations of each kind.
        """
        count_ops = {}
        for instr, _, _ in self.data:
            if instr.name in count_ops.keys():
                count_ops[instr.name] += 1
            else:
                count_ops[instr.name] = 1
        return count_ops

def count_ops ( self ) : count_ops = { } for instr , _ , _ in self . data : if instr . name in count_ops . keys ( ) : count_ops [ instr . name ] += 1 else : count_ops [ instr . name ] = 1 return count_ops

Count each operation kind in the circuit .


def num_connected_components(self, unitary_only=False):
        """How many non-entangled subcircuits can the circuit be factored to.

        Args:
            unitary_only (bool): Compute only unitary part of graph.

        Returns:
            int: Number of connected components in circuit.
        """
        # Convert registers to ints (as done in depth).
        reg_offset = 0
        reg_map = {}

        if unitary_only:
            regs = self.qregs
        else:
            regs = self.qregs+self.cregs

        for reg in regs:
            reg_map[reg.name] = reg_offset
            reg_offset += reg.size
        # Start with each qubit or cbit being its own subgraph.
        sub_graphs = [[bit] for bit in range(reg_offset)]

        num_sub_graphs = len(sub_graphs)

        # Here we are traversing the gates and looking to see
        # which of the sub_graphs the gate joins together.
        for instr, qargs, cargs in self.data:
            if unitary_only:
                args = qargs
                num_qargs = len(args)
            else:
                args = qargs+cargs
                num_qargs = len(args) + (1 if instr.control else 0)

            if num_qargs >= 2 and instr.name not in ['barrier', 'snapshot']:
                graphs_touched = []
                num_touched = 0
                # Controls necessarily join all the cbits in the
                # register that they use.
                if instr.control and not unitary_only:
                    creg = instr.control[0]
                    creg_int = reg_map[creg.name]
                    for coff in range(creg.size):
                        temp_int = creg_int+coff
                        for k in range(num_sub_graphs):
                            if temp_int in sub_graphs[k]:
                                graphs_touched.append(k)
                                num_touched += 1
                                break

                for item in args:
                    reg_int = reg_map[item[0].name]+item[1]
                    for k in range(num_sub_graphs):
                        if reg_int in sub_graphs[k]:
                            if k not in graphs_touched:
                                graphs_touched.append(k)
                                num_touched += 1
                                break

                # If the gate touches more than one subgraph
                # join those graphs together and return
                # reduced number of subgraphs
                if num_touched > 1:
                    connections = []
                    for idx in graphs_touched:
                        connections.extend(sub_graphs[idx])
                    _sub_graphs = []
                    for idx in range(num_sub_graphs):
                        if idx not in graphs_touched:
                            _sub_graphs.append(sub_graphs[idx])
                    _sub_graphs.append(connections)
                    sub_graphs = _sub_graphs
                    num_sub_graphs -= (num_touched-1)
            # Cannot go lower than one so break
            if num_sub_graphs == 1:
                break
        return num_sub_graphs

How many non - entangled subcircuits can the circuit be factored to .


def bind_parameters(self, value_dict):
        """Assign parameters to values yielding a new circuit.

        Args:
            value_dict (dict): {parameter: value, ...}

        Raises:
            QiskitError: If value_dict contains parameters not present in the circuit

        Returns:
            QuantumCircuit: copy of self with assignment substitution.
        """
        new_circuit = self.copy()

        if value_dict.keys() > self.parameters:
            raise QiskitError('Cannot bind parameters ({}) not present in the circuit.'.format(
                [str(p) for p in value_dict.keys() - self.parameters]))

        for parameter, value in value_dict.items():
            new_circuit._bind_parameter(parameter, value)
        # clear evaluated expressions
        for parameter in value_dict:
            del new_circuit._parameter_table[parameter]
        return new_circuit

Assign parameters to values yielding a new circuit .


def _bind_parameter(self, parameter, value):
        """Assigns a parameter value to matching instructions in-place."""
        for (instr, param_index) in self._parameter_table[parameter]:
            instr.params[param_index] = value

def _bind_parameter ( self , parameter , value ) : for ( instr , param_index ) in self . _parameter_table [ parameter ] : instr . params [ param_index ] = value

Assigns a parameter value to matching instructions in - place .


def pulse_drawer(samples, duration, dt=None, interp_method='None',
                 filename=None, interactive=False,
                 dpi=150, nop=1000, size=(6, 5)):
    """Plot the interpolated envelope of pulse

    Args:
        samples (ndarray): Data points of complex pulse envelope.
        duration (int): Pulse length (number of points).
        dt (float): Time interval of samples.
        interp_method (str): Method of interpolation
            (set `None` for turn off the interpolation).
        filename (str): Name required to save pulse image.
        interactive (bool): When set true show the circuit in a new window
            (this depends on the matplotlib backend being used supporting this).
        dpi (int): Resolution of saved image.
        nop (int): Data points for interpolation.
        size (tuple): Size of figure.
    Returns:
        matplotlib.figure: A matplotlib figure object for the pulse envelope.
    Raises:
        ImportError: when the output methods requieres non-installed libraries.
        QiskitError: when invalid interpolation method is specified.
    """

    try:
        from matplotlib import pyplot as plt
    except ImportError:
        raise ImportError('pulse_drawer need matplotlib. '
                          'Run "pip install matplotlib" before.')

    if dt:
        _dt = dt
    else:
        _dt = 1

    re_y = np.real(samples)
    im_y = np.imag(samples)

    image = plt.figure(figsize=size)
    ax0 = image.add_subplot(111)

    if interp_method == 'CubicSpline':
        # spline interpolation, use mid-point of dt
        time = np.arange(0, duration + 1) * _dt + 0.5 * _dt
        cs_ry = CubicSpline(time[:-1], re_y)
        cs_iy = CubicSpline(time[:-1], im_y)

        _time = np.linspace(0, duration * _dt, nop)
        _re_y = cs_ry(_time)
        _im_y = cs_iy(_time)
    elif interp_method == 'None':
        # pseudo-DAC output
        time = np.arange(0, duration + 1) * _dt

        _time = np.r_[time[0], np.repeat(time[1:-1], 2), time[-1]]
        _re_y = np.repeat(re_y, 2)
        _im_y = np.repeat(im_y, 2)
    else:
        raise QiskitError('Invalid interpolation method "%s"' % interp_method)

    # plot
    ax0.fill_between(x=_time, y1=_re_y, y2=np.zeros_like(_time),
                     facecolor='red', alpha=0.3,
                     edgecolor='red', linewidth=1.5,
                     label='real part')
    ax0.fill_between(x=_time, y1=_im_y, y2=np.zeros_like(_time),
                     facecolor='blue', alpha=0.3,
                     edgecolor='blue', linewidth=1.5,
                     label='imaginary part')

    ax0.set_xlim(0, duration * _dt)
    ax0.grid(b=True, linestyle='-')
    ax0.legend(bbox_to_anchor=(0.5, 1.00), loc='lower center',
               ncol=2, frameon=False, fontsize=14)

    if filename:
        image.savefig(filename, dpi=dpi, bbox_inches='tight')

    plt.close(image)

    if image and interactive:
        plt.show(image)

    return image


def _search_forward_n_swaps(layout, gates, coupling_map,
                            depth=SEARCH_DEPTH, width=SEARCH_WIDTH):
    """Search for SWAPs which allow for application of largest number of gates.

    Arguments:
        layout (Layout): Map from virtual qubit index to physical qubit index.
        gates (list): Gates to be mapped.
        coupling_map (CouplingMap): CouplingMap of the target backend.
        depth (int): Number of SWAP layers to search before choosing a result.
        width (int): Number of SWAPs to consider at each layer.
    Returns:
        dict: Describes solution step found.
            layout (Layout): Virtual to physical qubit map after SWAPs.
            gates_remaining (list): Gates that could not be mapped.
            gates_mapped (list): Gates that were mapped, including added SWAPs.

    """

    gates_mapped, gates_remaining = _map_free_gates(layout, gates, coupling_map)

    base_step = {'layout': layout,
                 'swaps_added': 0,
                 'gates_mapped': gates_mapped,
                 'gates_remaining': gates_remaining}

    if not gates_remaining or depth == 0:
        return base_step

    possible_swaps = coupling_map.get_edges()

    def _score_swap(swap):
        """Calculate the relative score for a given SWAP."""
        trial_layout = layout.copy()
        trial_layout.swap(*swap)
        return _calc_layout_distance(gates, coupling_map, trial_layout)

    ranked_swaps = sorted(possible_swaps, key=_score_swap)

    best_swap, best_step = None, None
    for swap in ranked_swaps[:width]:
        trial_layout = layout.copy()
        trial_layout.swap(*swap)
        next_step = _search_forward_n_swaps(trial_layout, gates_remaining,
                                            coupling_map, depth - 1, width)

        # ranked_swaps already sorted by distance, so distance is the tie-breaker.
        if best_swap is None or _score_step(next_step) > _score_step(best_step):
            best_swap, best_step = swap, next_step

    best_swap_gate = _swap_ops_from_edge(best_swap, layout)
    return {
        'layout': best_step['layout'],
        'swaps_added': 1 + best_step['swaps_added'],
        'gates_remaining': best_step['gates_remaining'],
        'gates_mapped': gates_mapped + best_swap_gate + best_step['gates_mapped'],
    }

Search for SWAPs which allow for application of largest number of gates .


def _map_free_gates(layout, gates, coupling_map):
    """Map all gates that can be executed with the current layout.

    Args:
        layout (Layout): Map from virtual qubit index to physical qubit index.
        gates (list): Gates to be mapped.
        coupling_map (CouplingMap): CouplingMap for target device topology.

    Returns:
        tuple:
            mapped_gates (list): ops for gates that can be executed, mapped onto layout.
            remaining_gates (list): gates that cannot be executed on the layout.

    """

    blocked_qubits = set()

    mapped_gates = []
    remaining_gates = []

    for gate in gates:
        # Gates without a partition (barrier, snapshot, save, load, noise) may
        # still have associated qubits. Look for them in the qargs.
        if not gate['partition']:
            qubits = [n for n in gate['graph'].nodes() if n.type == 'op'][0].qargs

            if not qubits:
                continue

            if blocked_qubits.intersection(qubits):
                blocked_qubits.update(qubits)
                remaining_gates.append(gate)
            else:
                mapped_gate = _transform_gate_for_layout(gate, layout)
                mapped_gates.append(mapped_gate)
            continue

        qubits = gate['partition'][0]

        if blocked_qubits.intersection(qubits):
            blocked_qubits.update(qubits)
            remaining_gates.append(gate)
        elif len(qubits) == 1:
            mapped_gate = _transform_gate_for_layout(gate, layout)
            mapped_gates.append(mapped_gate)
        elif coupling_map.distance(*[layout[q] for q in qubits]) == 1:
            mapped_gate = _transform_gate_for_layout(gate, layout)
            mapped_gates.append(mapped_gate)
        else:
            blocked_qubits.update(qubits)
            remaining_gates.append(gate)

    return mapped_gates, remaining_gates

Map all gates that can be executed with the current layout .


def _calc_layout_distance(gates, coupling_map, layout, max_gates=None):
    """Return the sum of the distances of two-qubit pairs in each CNOT in gates
    according to the layout and the coupling.
    """

    if max_gates is None:
        max_gates = 50 + 10 * len(coupling_map.physical_qubits)

    return sum(coupling_map.distance(*[layout[q] for q in gate['partition'][0]])
               for gate in gates[:max_gates]
               if gate['partition'] and len(gate['partition'][0]) == 2)

def _calc_layout_distance ( gates , coupling_map , layout , max_gates = None ) : if max_gates is None : max_gates = 50 + 10 * len ( coupling_map . physical_qubits ) return sum ( coupling_map . distance ( * [ layout [ q ] for q in gate [ 'partition' ] [ 0 ] ] ) for gate in gates [ : max_gates ] if gate [ 'partition' ] and len ( gate [ 'partition' ] [ 0 ] ) == 2 )

Return the sum of the distances of two - qubit pairs in each CNOT in gates according to the layout and the coupling .


def _score_step(step):

    """Count the mapped two-qubit gates, less the number of added SWAPs."""
    # Each added swap will add 3 ops to gates_mapped, so subtract 3.
    return len([g for g in step['gates_mapped']
                if len(g.qargs) == 2]) - 3 * step['swaps_added']

Count the mapped two - qubit gates less the number of added SWAPs .


def _copy_circuit_metadata(source_dag, coupling_map):
    """Return a copy of source_dag with metadata but empty.
    Generate only a single qreg in the output DAG, matching the size of the
    coupling_map."""

    target_dag = DAGCircuit()
    target_dag.name = source_dag.name

    for creg in source_dag.cregs.values():
        target_dag.add_creg(creg)

    device_qreg = QuantumRegister(len(coupling_map.physical_qubits), 'q')
    target_dag.add_qreg(device_qreg)

    return target_dag

def _copy_circuit_metadata ( source_dag , coupling_map ) : target_dag = DAGCircuit ( ) target_dag . name = source_dag . name for creg in source_dag . cregs . values ( ) : target_dag . add_creg ( creg ) device_qreg = QuantumRegister ( len ( coupling_map . physical_qubits ) , 'q' ) target_dag . add_qreg ( device_qreg ) return target_dag

Return a copy of source_dag with metadata but empty . Generate only a single qreg in the output DAG matching the size of the coupling_map .


def _transform_gate_for_layout(gate, layout):
    """Return op implementing a virtual gate on given layout."""

    mapped_op_node = deepcopy([n for n in gate['graph'].nodes() if n.type == 'op'][0])

    # Workaround until #1816, apply mapped to qargs to both DAGNode and op
    device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
    mapped_qargs = [(device_qreg, layout[a]) for a in mapped_op_node.qargs]
    mapped_op_node.qargs = mapped_op_node.op.qargs = mapped_qargs

    mapped_op_node.pop('name')

    return mapped_op_node

Return op implementing a virtual gate on given layout .


def _swap_ops_from_edge(edge, layout):
    """Generate list of ops to implement a SWAP gate along a coupling edge."""

    device_qreg = QuantumRegister(len(layout.get_physical_bits()), 'q')
    qreg_edge = [(device_qreg, i) for i in edge]

    # TODO shouldn't be making other nodes not by the DAG!!
    return [
        DAGNode({'op': SwapGate(), 'qargs': qreg_edge, 'cargs': [], 'type': 'op'})
    ]

Generate list of ops to implement a SWAP gate along a coupling edge .


def run(self, dag):
        """Run one pass of the lookahead mapper on the provided DAG.

        Args:
            dag (DAGCircuit): the directed acyclic graph to be mapped
        Returns:
            DAGCircuit: A dag mapped to be compatible with the coupling_map in
                the property_set.
        Raises:
            TranspilerError: if the coupling map or the layout are not
            compatible with the DAG
        """
        coupling_map = self._coupling_map
        ordered_virtual_gates = list(dag.serial_layers())

        if self.initial_layout is None:
            if self.property_set["layout"]:
                self.initial_layout = self.property_set["layout"]
            else:
                self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())

        if len(dag.qubits()) != len(self.initial_layout):
            raise TranspilerError('The layout does not match the amount of qubits in the DAG')

        if len(self._coupling_map.physical_qubits) != len(self.initial_layout):
            raise TranspilerError(
                "Mappers require to have the layout to be the same size as the coupling map")

        mapped_gates = []
        layout = self.initial_layout.copy()
        gates_remaining = ordered_virtual_gates.copy()

        while gates_remaining:
            best_step = _search_forward_n_swaps(layout, gates_remaining,
                                                coupling_map)

            layout = best_step['layout']
            gates_mapped = best_step['gates_mapped']
            gates_remaining = best_step['gates_remaining']

            mapped_gates.extend(gates_mapped)

        # Preserve input DAG's name, regs, wire_map, etc. but replace the graph.
        mapped_dag = _copy_circuit_metadata(dag, coupling_map)

        for node in mapped_gates:
            mapped_dag.apply_operation_back(op=node.op, qargs=node.qargs, cargs=node.cargs)

        return mapped_dag

Run one pass of the lookahead mapper on the provided DAG .


def add_physical_qubit(self, physical_qubit):
        """Add a physical qubit to the coupling graph as a node.

        physical_qubit (int): An integer representing a physical qubit.

        Raises:
            CouplingError: if trying to add duplicate qubit
        """
        if not isinstance(physical_qubit, int):
            raise CouplingError("Physical qubits should be integers.")
        if physical_qubit in self.physical_qubits:
            raise CouplingError(
                "The physical qubit %s is already in the coupling graph" % physical_qubit)
        self.graph.add_node(physical_qubit)
        self._dist_matrix = None  # invalidate
        self._qubit_list = None

Add a physical qubit to the coupling graph as a node .


def add_edge(self, src, dst):
        """
        Add directed edge to coupling graph.

        src (int): source physical qubit
        dst (int): destination physical qubit
        """
        if src not in self.physical_qubits:
            self.add_physical_qubit(src)
        if dst not in self.physical_qubits:
            self.add_physical_qubit(dst)
        self.graph.add_edge(src, dst)
        self._dist_matrix = None

def add_edge ( self , src , dst ) : if src not in self . physical_qubits : self . add_physical_qubit ( src ) if dst not in self . physical_qubits : self . add_physical_qubit ( dst ) self . graph . add_edge ( src , dst ) self . _dist_matrix = None


def subgraph(self, nodelist):
        """Return a CouplingMap object for a subgraph of self.

        nodelist (list): list of integer node labels
        """
        subcoupling = CouplingMap()
        subcoupling.graph = self.graph.subgraph(nodelist)
        for node in nodelist:
            if node not in subcoupling.physical_qubits:
                subcoupling.add_physical_qubit(node)
        return subcoupling

def subgraph ( self , nodelist ) : subcoupling = CouplingMap ( ) subcoupling . graph = self . graph . subgraph ( nodelist ) for node in nodelist : if node not in subcoupling . physical_qubits : subcoupling . add_physical_qubit ( node ) return subcoupling

Return a CouplingMap object for a subgraph of self .


def physical_qubits(self):
        """Returns a sorted list of physical_qubits"""
        if self._qubit_list is None:
            self._qubit_list = sorted([pqubit for pqubit in self.graph.nodes])
        return self._qubit_list

def physical_qubits ( self ) : if self . _qubit_list is None : self . _qubit_list = sorted ( [ pqubit for pqubit in self . graph . nodes ] ) return self . _qubit_list


def is_connected(self):
        """
        Test if the graph is connected.

        Return True if connected, False otherwise
        """
        try:
            return nx.is_weakly_connected(self.graph)
        except nx.exception.NetworkXException:
            return False

def is_connected ( self ) : try : return nx . is_weakly_connected ( self . graph ) except nx . exception . NetworkXException : return False


def _compute_distance_matrix(self):
        """Compute the full distance matrix on pairs of nodes.

        The distance map self._dist_matrix is computed from the graph using
        all_pairs_shortest_path_length.
        """
        if not self.is_connected():
            raise CouplingError("coupling graph not connected")
        lengths = nx.all_pairs_shortest_path_length(self.graph.to_undirected(as_view=True))
        lengths = dict(lengths)
        size = len(lengths)
        cmap = np.zeros((size, size))
        for idx in range(size):
            cmap[idx, np.fromiter(lengths[idx].keys(), dtype=int)] = np.fromiter(
                lengths[idx].values(), dtype=int)
        self._dist_matrix = cmap

def
_compute_distance_matrix
(
self
)
:
if
not
self
.
is_connected
(
)
:
raise
CouplingError
(
"coupling graph not connected"
)
lengths
=
nx
.
all_pairs_shortest_path_length
(
self
.
graph
.
to_undirected
(
as_view
=
True
)
)
lengths
=
dict
(
lengths
)
size
=
len
(
lengths
)
cmap
=
np
.
zeros
(
(
size
,
size
)
)
for
idx
in
range
(
size
)
:
cmap
[
idx
,
np
.
fromiter
(
lengths
[
idx
]
.
keys
(
)
,
dtype
=
int
)
]
=
np
.
fromiter
(
lengths
[
idx
]
.
values
(
)
,
dtype
=
int
)
self
.
_dist_matrix
=
cmap

Compute the full distance matrix on pairs of nodes .


def distance(self, physical_qubit1, physical_qubit2):
        """Returns the undirected distance between physical_qubit1 and physical_qubit2.

        Args:
            physical_qubit1 (int): A physical qubit
            physical_qubit2 (int): Another physical qubit

        Returns:
            int: The undirected distance

        Raises:
            CouplingError: if the qubits do not exist in the CouplingMap
        """
        if physical_qubit1 not in self.physical_qubits:
            raise CouplingError("%s not in coupling graph" % (physical_qubit1,))
        if physical_qubit2 not in self.physical_qubits:
            raise CouplingError("%s not in coupling graph" % (physical_qubit2,))
        if self._dist_matrix is None:
            self._compute_distance_matrix()
        return self._dist_matrix[physical_qubit1, physical_qubit2]

def
distance
(
self
,
physical_qubit1
,
physical_qubit2
)
:
if
physical_qubit1
not
in
self
.
physical_qubits
:
raise
CouplingError
(
"%s not in coupling graph"
%
(
physical_qubit1
,
)
)
if
physical_qubit2
not
in
self
.
physical_qubits
:
raise
CouplingError
(
"%s not in coupling graph"
%
(
physical_qubit2
,
)
)
if
self
.
_dist_matrix
is
:
self
.
_compute_distance_matrix
(
)
return
self
.
_dist_matrix
[
physical_qubit1
,
physical_qubit2
]

Returns the undirected distance between physical_qubit1 and physical_qubit2 .


def transpile(circuits, backend=None, basis_gates=None, coupling_map=None,
              initial_layout=None, seed_mapper=None, pass_manager=None):
    """transpile one or more circuits.

    Args:
        circuits (QuantumCircuit or list[QuantumCircuit]): circuits to compile
        backend (BaseBackend): a backend to compile for
        basis_gates (list[str]): list of basis gate names supported by the
            target. Default: ['u1','u2','u3','cx','id']
        coupling_map (list): coupling map (perhaps custom) to target in mapping

        initial_layout (Layout or dict or list):
            Initial position of virtual qubits on physical qubits. The final
            layout is not guaranteed to be the same, as the transpiler may permute
            qubits through swaps or other means.

        seed_mapper (int): random seed for the swap_mapper
        pass_manager (PassManager): a pass_manager for the transpiler stages

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

    Raises:
        TranspilerError: in case of bad inputs to transpiler or errors in passes
    """
    warnings.warn("qiskit.transpiler.transpile() has been deprecated and will be "
                  "removed in the 0.9 release. Use qiskit.compiler.transpile() instead.",
                  DeprecationWarning)
    return compiler.transpile(circuits=circuits, backend=backend,
                              basis_gates=basis_gates, coupling_map=coupling_map,
                              initial_layout=initial_layout, seed_transpiler=seed_mapper,
                              pass_manager=pass_manager)


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

def cu1 ( self , theta , ctl , tgt ) : return self . append ( Cu1Gate ( theta ) , [ ctl , tgt ] , [ ] )

Apply cu1 from ctl to tgt with angle theta .


def inverse(self):
        """Invert all instructions."""
        for index, instruction in enumerate(self.instructions):
            self.instructions[index] = instruction.inverse()
        return self

def inverse ( self ) : for index , instruction in enumerate ( self . instructions ) : self . instructions [ index ] = instruction . inverse ( ) return self


def q_if(self, *qregs):
        """Add controls to all instructions."""
        for gate in self.instructions:
            gate.q_if(*qregs)
        return self

def q_if ( self , * qregs ) : for gate in self . instructions : gate . q_if ( * qregs ) return self


def c_if(self, classical, val):
        """Add classical control register to all instructions."""
        for gate in self.instructions:
            gate.c_if(classical, val)
        return self

def c_if ( self , classical , val ) : for gate in self . instructions : gate . c_if ( classical , val ) return self

Add classical control register to all instructions .


def subscribe(self, event, callback):
        """Subscribes to an event, so when it's emitted all the callbacks subscribed,
        will be executed. We are not allowing double registration.

        Args
            event (string): The event to subscribed in the form of:
                            "terra.<component>.<method>.<action>"
            callback (callable): The callback that will be executed when an event is
                                  emitted.
        """
        if not callable(callback):
            raise QiskitError("Callback is not a callable!")

        if event not in self._subscribers:
            self._subscribers[event] = []

        new_subscription = self._Subscription(event, callback)
        if new_subscription in self._subscribers[event]:
            # We are not allowing double subscription
            return False

        self._subscribers[event].append(new_subscription)
        return True

Subscribes to an event so when it s emitted all the callbacks subscribed will be executed . We are not allowing double registration .


def dispatch(self, event, *args, **kwargs):
        """Emits an event if there are any subscribers.

        Args
            event (String): The event to be emitted
            args: Arguments linked with the event
            kwargs: Named arguments linked with the event
        """
        # No event, no subscribers.
        if event not in self._subscribers:
            return

        for subscriber in self._subscribers[event]:
            subscriber.callback(*args, **kwargs)

def
dispatch
(
self
,
event
,
*
args
,
*
*
kwargs
)
:
# No event, no subscribers.
if
event
not
in
self
.
_subscribers
:
return
for
subscriber
in
self
.
_subscribers
[
event
]
:
subscriber
.
callback
(
*
args
,
*
*
kwargs
)

Emits an event if there are any subscribers .


def unsubscribe(self, event, callback):
        """ Unsubscribe the specific callback to the event.

        Args
            event (String): The event to unsubscribe
            callback (callable): The callback that won't be executed anymore

        Returns
            True: if we have successfully unsubscribed to the event
            False: if there's no callback previously registered
        """

        try:
            self._subscribers[event].remove(self._Subscription(event, callback))
        except KeyError:
            return False

        return True

def unsubscribe ( self , event , callback ) : try : self . _subscribers [ event ] . remove ( self . _Subscription ( event , callback ) ) except KeyError : return False return True

Unsubscribe the specific callback to the event .


def publish(self, event, *args, **kwargs):
        """ Triggers an event, and associates some data to it, so if there are any
        subscribers, their callback will be called synchronously. """
        return self._broker.dispatch(event, *args, **kwargs)

def publish ( self , event , * args , * * kwargs ) : return self . _broker . dispatch ( event , * args , * * kwargs )

Triggers an event and associates some data to it so if there are any subscribers their callback will be called synchronously .


def initialize(self, params, qubits):
    """Apply initialize to circuit."""
    if isinstance(qubits, QuantumRegister):
        qubits = qubits[:]
    else:
        qubits = _convert_to_bits([qubits], [qbit for qreg in self.qregs for qbit in qreg])[0]
    return self.append(Initialize(params), qubits)

def initialize ( self , params , qubits ) : if isinstance ( qubits , QuantumRegister ) : qubits = qubits [ : ] else : qubits = _convert_to_bits ( [ qubits ] , [ qbit for qreg in self . qregs for qbit in qreg ] ) [ 0 ] return self . append ( Initialize ( params ) , qubits )


def _define(self):
        """Calculate a subcircuit that implements this initialization

        Implements a recursive initialization algorithm, including optimizations,
        from "Synthesis of Quantum Logic Circuits" Shende, Bullock, Markov
        https://arxiv.org/abs/quant-ph/0406176v5

        Additionally implements some extra optimizations: remove zero rotations and
        double cnots.
        """
        # call to generate the circuit that takes the desired vector to zero
        disentangling_circuit = self.gates_to_uncompute()

        # invert the circuit to create the desired vector from zero (assuming
        # the qubits are in the zero state)
        initialize_instr = disentangling_circuit.to_instruction().inverse()

        q = QuantumRegister(self.num_qubits, 'q')
        initialize_circuit = QuantumCircuit(q, name='init_def')
        for qubit in q:
            initialize_circuit.append(Reset(), [qubit])
        initialize_circuit.append(initialize_instr, q[:])

        self.definition = initialize_circuit.data


def gates_to_uncompute(self):
        """
        Call to create a circuit with gates that take the
        desired vector to zero.

        Returns:
            QuantumCircuit: circuit to take self.params vector to |00..0>
        """
        q = QuantumRegister(self.num_qubits)
        circuit = QuantumCircuit(q, name='disentangler')

        # kick start the peeling loop, and disentangle one-by-one from LSB to MSB
        remaining_param = self.params

        for i in range(self.num_qubits):
            # work out which rotations must be done to disentangle the LSB
            # qubit (we peel away one qubit at a time)
            (remaining_param,
             thetas,
             phis) = Initialize._rotations_to_disentangle(remaining_param)

            # perform the required rotations to decouple the LSB qubit (so that
            # it can be "factored" out, leaving a shorter amplitude vector to peel away)
            rz_mult = self._multiplex(RZGate, phis)
            ry_mult = self._multiplex(RYGate, thetas)
            circuit.append(rz_mult.to_instruction(), q[i:self.num_qubits])
            circuit.append(ry_mult.to_instruction(), q[i:self.num_qubits])
        return circuit

Call to create a circuit with gates that take the desired vector to zero .


def _bloch_angles(pair_of_complex):
        """
        Static internal method to work out rotation to create the passed in
        qubit from the zero vector.
        """
        [a_complex, b_complex] = pair_of_complex
        # Force a and b to be complex, as otherwise numpy.angle might fail.
        a_complex = complex(a_complex)
        b_complex = complex(b_complex)
        mag_a = np.absolute(a_complex)
        final_r = float(np.sqrt(mag_a ** 2 + np.absolute(b_complex) ** 2))
        if final_r < _EPS:
            theta = 0
            phi = 0
            final_r = 0
            final_t = 0
        else:
            theta = float(2 * np.arccos(mag_a / final_r))
            a_arg = np.angle(a_complex)
            b_arg = np.angle(b_complex)
            final_t = a_arg + b_arg
            phi = b_arg - a_arg

        return final_r * np.exp(1.J * final_t / 2), theta, phi

Static internal method to work out rotation to create the passed in qubit from the zero vector .


def _multiplex(self, target_gate, list_of_angles):
        """
        Return a recursive implementation of a multiplexor circuit,
        where each instruction itself has a decomposition based on
        smaller multiplexors.

        The LSB is the multiplexor "data" and the other bits are multiplexor "select".

        Args:
            target_gate (Gate): Ry or Rz gate to apply to target qubit, multiplexed
                over all other "select" qubits
            list_of_angles (list[float]): list of rotation angles to apply Ry and Rz

        Returns:
            DAGCircuit: the circuit implementing the multiplexor's action
        """
        list_len = len(list_of_angles)
        local_num_qubits = int(math.log2(list_len)) + 1

        q = QuantumRegister(local_num_qubits)
        circuit = QuantumCircuit(q, name="multiplex" + local_num_qubits.__str__())

        lsb = q[0]
        msb = q[local_num_qubits - 1]

        # case of no multiplexing: base case for recursion
        if local_num_qubits == 1:
            circuit.append(target_gate(list_of_angles[0]), [q[0]])
            return circuit

        # calc angle weights, assuming recursion (that is the lower-level
        # requested angles have been correctly implemented by recursion
        angle_weight = scipy.kron([[0.5, 0.5], [0.5, -0.5]],
                                  np.identity(2 ** (local_num_qubits - 2)))

        # calc the combo angles
        list_of_angles = angle_weight.dot(np.array(list_of_angles)).tolist()

        # recursive step on half the angles fulfilling the above assumption
        multiplex_1 = self._multiplex(target_gate, list_of_angles[0:(list_len // 2)])
        circuit.append(multiplex_1.to_instruction(), q[0:-1])

        # attach CNOT as follows, thereby flipping the LSB qubit
        circuit.append(CnotGate(), [msb, lsb])

        # implement extra efficiency from the paper of cancelling adjacent
        # CNOTs (by leaving out last CNOT and reversing (NOT inverting) the
        # second lower-level multiplex)
        multiplex_2 = self._multiplex(target_gate, list_of_angles[(list_len // 2):])
        if list_len > 1:
            circuit.append(multiplex_2.to_instruction().mirror(), q[0:-1])
        else:
            circuit.append(multiplex_2.to_instruction(), q[0:-1])

        # attach a final CNOT
        circuit.append(CnotGate(), [msb, lsb])

        return circuit

Return a recursive implementation of a multiplexor circuit where each instruction itself has a decomposition based on smaller multiplexors .


def is_virtual(value):
        """Checks if value has the format of a virtual qubit """
        return value is None or isinstance(value, tuple) and len(value) == 2 and isinstance(
            value[0], Register) and isinstance(value[1], int)

def is_virtual ( value ) : return value is None or isinstance ( value , tuple ) and len ( value ) == 2 and isinstance ( value [ 0 ] , Register ) and isinstance ( value [ 1 ] , int )


def copy(self):
        """Returns a copy of a Layout instance."""
        layout_copy = type(self)()

        layout_copy._p2v = self._p2v.copy()
        layout_copy._v2p = self._v2p.copy()

        return layout_copy

def copy ( self ) : layout_copy = type ( self ) ( ) layout_copy . _p2v = self . _p2v . copy ( ) layout_copy . _v2p = self . _v2p . copy ( ) return layout_copy


def combine_into_edge_map(self, another_layout):
        """Combines self and another_layout into an "edge map".

        For example::

              self       another_layout  resulting edge map
           qr_1 -> 0        0 <- q_2         qr_1 -> q_2
           qr_2 -> 2        2 <- q_1         qr_2 -> q_1
           qr_3 -> 3        3 <- q_0         qr_3 -> q_0

        The edge map is used to compose dags via, for example, compose_back.

        Args:
            another_layout (Layout): The other layout to combine.
        Returns:
            dict: A "edge map".
        Raises:
            LayoutError: another_layout can be bigger than self, but not smaller. Otherwise, raises.
        """
        edge_map = dict()

        for virtual, physical in self.get_virtual_bits().items():
            if physical not in another_layout._p2v:
                raise LayoutError('The wire_map_from_layouts() method does not support when the'
                                  ' other layout (another_layout) is smaller.')
            edge_map[virtual] = another_layout[physical]

        return edge_map

Combines self and another_layout into an edge map .


def ccx(self, ctl1, ctl2, tgt):
    """Apply Toffoli to from ctl1 and ctl2 to tgt."""
    return self.append(ToffoliGate(), [ctl1, ctl2, tgt], [])

def ccx ( self , ctl1 , ctl2 , tgt ) : return self . append ( ToffoliGate ( ) , [ ctl1 , ctl2 , tgt ] , [ ] )

Apply Toffoli to from ctl1 and ctl2 to tgt .


def insert(self, start_time: int, schedule: ScheduleComponent) -> 'ScheduleComponent':
        """Return a new schedule with `schedule` inserted within `self` at `start_time`.

        Args:
            start_time: time to be inserted
            schedule: schedule to be inserted
        """
        return ops.insert(self, start_time, schedule)

def insert ( self , start_time : int , schedule : ScheduleComponent ) -> 'ScheduleComponent' : return ops . insert ( self , start_time , schedule )

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


def _check_if_fenced(self, name):
        """
        Checks if the attribute name is in the list of attributes to protect. If so, raises
        TranspilerAccessError.

        Args:
            name (string): the attribute name to check

        Raises:
            TranspilerAccessError: when name is the list of attributes to protect.
        """
        if name in object.__getattribute__(self, '_attributes_to_fence'):
            raise TranspilerAccessError("The fenced %s has the property %s protected" %
                                        (type(object.__getattribute__(self, '_wrapped')), name))

Checks if the attribute name is in the list of attributes to protect . If so raises TranspilerAccessError .


def gates_to_idx(gates, qregs):
    """Converts gate tuples into a nested list of integers.

    Args:
        gates (list): List of (QuantumRegister, int) pairs
                      representing gates.
        qregs (dict): List of )QuantumRegister, int) tuples.

    Returns:
        list: Nested list of integers for gates.
    """
    sizes = [qr.size for qr in qregs.values()]
    reg_idx = np.cumsum([0]+sizes)
    regint = {}
    for ind, qreg in enumerate(qregs.values()):
        regint[qreg] = ind
    out = np.zeros(2*len(gates), dtype=np.int32)
    for idx, gate in enumerate(gates):
        out[2*idx] = reg_idx[regint[gate[0][0]]]+gate[0][1]
        out[2*idx+1] = reg_idx[regint[gate[1][0]]]+gate[1][1]
    return out

def gates_to_idx ( gates , qregs ) : sizes = [ qr . size for qr in qregs . values ( ) ] reg_idx = np . cumsum ( [ 0 ] + sizes ) regint = { } for ind , qreg in enumerate ( qregs . values ( ) ) : regint [ qreg ] = ind out = np . zeros ( 2 * len ( gates ) , dtype = np . int32 ) for idx , gate in enumerate ( gates ) : out [ 2 * idx ] = reg_idx [ regint [ gate [ 0 ] [ 0 ] ] ] + gate [ 0 ] [ 1 ] out [ 2 * idx + 1 ] = reg_idx [ regint [ gate [ 1 ] [ 0 ] ] ] + gate [ 1 ] [ 1 ] return out

Converts gate tuples into a nested list of integers .


def run(self, dag):
        """
        Run the StochasticSwap pass on `dag`.

        Args:
            dag (DAGCircuit): DAG to map.

        Returns:
            DAGCircuit: A mapped DAG.

        Raises:
            TranspilerError: if the coupling map or the layout are not
            compatible with the DAG
        """

        if self.initial_layout is None:
            if self.property_set["layout"]:
                self.initial_layout = self.property_set["layout"]
            else:
                self.initial_layout = Layout.generate_trivial_layout(*dag.qregs.values())

        if len(dag.qubits()) != len(self.initial_layout):
            raise TranspilerError('The layout does not match the amount of qubits in the DAG')

        if len(self.coupling_map.physical_qubits) != len(self.initial_layout):
            raise TranspilerError(
                "Mappers require to have the layout to be the same size as the coupling map")

        self.input_layout = self.initial_layout.copy()

        self.qregs = dag.qregs
        if self.seed is None:
            self.seed = np.random.randint(0, np.iinfo(np.int32).max)
        self.rng = np.random.RandomState(self.seed)
        logger.debug("StochasticSwap RandomState seeded with seed=%s", self.seed)

        new_dag = self._mapper(dag, self.coupling_map, trials=self.trials)
        # self.property_set["layout"] = self.initial_layout
        return new_dag


def _layer_update(self, i, first_layer, best_layout, best_depth,
                      best_circuit, layer_list):
        """Provide a DAGCircuit for a new mapped layer.

        i (int) = layer number
        first_layer (bool) = True if this is the first layer in the
            circuit with any multi-qubit gates
        best_layout (Layout) = layout returned from _layer_permutation
        best_depth (int) = depth returned from _layer_permutation
        best_circuit (DAGCircuit) = swap circuit returned
            from _layer_permutation
        layer_list (list) = list of DAGCircuit objects for each layer,
            output of DAGCircuit layers() method

        Return a DAGCircuit object to append to the output DAGCircuit
        that the _mapper method is building.
        """
        layout = best_layout
        logger.debug("layer_update: layout = %s", pformat(layout))
        logger.debug("layer_update: self.initial_layout = %s", pformat(self.initial_layout))
        dagcircuit_output = DAGCircuit()
        for register in layout.get_virtual_bits().keys():
            if register[0] not in dagcircuit_output.qregs.values():
                dagcircuit_output.add_qreg(register[0])

        # If this is the first layer with multi-qubit gates,
        # output all layers up to this point and ignore any
        # swap gates. Set the initial layout.
        if first_layer:
            logger.debug("layer_update: first multi-qubit gate layer")
            # Output all layers up to this point
            for j in range(i + 1):
                # Make qubit edge map and extend by classical bits
                edge_map = layout.combine_into_edge_map(self.initial_layout)
                for bit in dagcircuit_output.clbits():
                    edge_map[bit] = bit
                dagcircuit_output.compose_back(layer_list[j]["graph"], edge_map)
        # Otherwise, we output the current layer and the associated swap gates.
        else:
            # Output any swaps
            if best_depth > 0:
                logger.debug("layer_update: there are swaps in this layer, "
                             "depth %d", best_depth)
                dagcircuit_output.extend_back(best_circuit)
            else:
                logger.debug("layer_update: there are no swaps in this layer")
            # Make qubit edge map and extend by classical bits
            edge_map = layout.combine_into_edge_map(self.initial_layout)
            for bit in dagcircuit_output.clbits():
                edge_map[bit] = bit
            # Output this layer
            dagcircuit_output.compose_back(layer_list[i]["graph"], edge_map)

        return dagcircuit_output

Provide a DAGCircuit for a new mapped layer .


def pauli_group(number_of_qubits, case='weight'):
    """Return the Pauli group with 4^n elements.

    The phases have been removed.
    case 'weight' is ordered by Pauli weights and
    case 'tensor' is ordered by I,X,Y,Z counting lowest qubit fastest.

    Args:
        number_of_qubits (int): number of qubits
        case (str): determines ordering of group elements ('weight' or 'tensor')

    Returns:
        list: list of Pauli objects

    Raises:
        QiskitError: case is not 'weight' or 'tensor'
        QiskitError: number_of_qubits is larger than 4
    """
    if number_of_qubits < 5:
        temp_set = []

        if case == 'weight':
            tmp = pauli_group(number_of_qubits, case='tensor')
            # sort on the weight of the Pauli operator
            return sorted(tmp, key=lambda x: -np.count_nonzero(
                np.array(x.to_label(), 'c') == b'I'))
        elif case == 'tensor':
            # the Pauli set is in tensor order II IX IY IZ XI ...
            for k in range(4 ** number_of_qubits):
                z = np.zeros(number_of_qubits, dtype=np.bool)
                x = np.zeros(number_of_qubits, dtype=np.bool)
                # looping over all the qubits
                for j in range(number_of_qubits):
                    # making the Pauli for each j fill it in from the
                    # end first
                    element = (k // (4 ** j)) % 4
                    if element == 1:
                        x[j] = True
                    elif element == 2:
                        z[j] = True
                        x[j] = True
                    elif element == 3:
                        z[j] = True
                temp_set.append(Pauli(z, x))
            return temp_set
        else:
            raise QiskitError("Only support 'weight' or 'tensor' cases "
                              "but you have {}.".format(case))

    raise QiskitError("Only support number of qubits is less than 5")

Return the Pauli group with 4^n elements .


def from_label(cls, label):
        r"""Take pauli string to construct pauli.

        The qubit index of pauli label is q_{n-1} ... q_0.
        E.g., a pauli is $P_{n-1} \otimes ... \otimes P_0$

        Args:
            label (str): pauli label

        Returns:
            Pauli: the constructed pauli

        Raises:
            QiskitError: invalid character in the label
        """
        z = np.zeros(len(label), dtype=np.bool)
        x = np.zeros(len(label), dtype=np.bool)
        for i, char in enumerate(label):
            if char == 'X':
                x[-i - 1] = True
            elif char == 'Z':
                z[-i - 1] = True
            elif char == 'Y':
                z[-i - 1] = True
                x[-i - 1] = True
            elif char != 'I':
                raise QiskitError("Pauli string must be only consisted of 'I', 'X', "
                                  "'Y' or 'Z' but you have {}.".format(char))
        return cls(z=z, x=x)

r Take pauli string to construct pauli .


def _init_from_bool(self, z, x):
        """Construct pauli from boolean array.

        Args:
            z (numpy.ndarray): boolean, z vector
            x (numpy.ndarray): boolean, x vector

        Returns:
            Pauli: self

        Raises:
            QiskitError: if z or x are None or the length of z and x are different.
        """
        if z is None:
            raise QiskitError("z vector must not be None.")
        if x is None:
            raise QiskitError("x vector must not be None.")
        if len(z) != len(x):
            raise QiskitError("length of z and x vectors must be "
                              "the same. (z: {} vs x: {})".format(len(z), len(x)))

        z = _make_np_bool(z)
        x = _make_np_bool(x)
        self._z = z
        self._x = x

        return self

def
_init_from_bool
(
self
,
z
,
x
)
:
if
z
is
:
raise
QiskitError
(
"z vector must not be None."
)
if
x
is
:
raise
QiskitError
(
"x vector must not be None."
)
if
len
(
z
)
!=
len
(
x
)
:
raise
QiskitError
(
"length of z and x vectors must be "
"the same. (z: {} vs x: {})"
.
format
(
len
(
z
)
,
len
(
x
)
)
)
z
=
_make_np_bool
(
z
)
x
=
_make_np_bool
(
x
)
self
.
_z
=
z
self
.
_x
=
x
return
self


def sgn_prod(p1, p2):
        r"""
        Multiply two Paulis and track the phase.

        $P_3 = P_1 \otimes P_2$: X*Y

        Args:
            p1 (Pauli): pauli 1
            p2 (Pauli): pauli 2

        Returns:
            Pauli: the multiplied pauli
            complex: the sign of the multiplication, 1, -1, 1j or -1j
        """
        phase = Pauli._prod_phase(p1, p2)
        new_pauli = p1 * p2
        return new_pauli, phase

r Multiply two Paulis and track the phase .


def to_operator(self):
        """Convert to Operator object."""
        # Place import here to avoid cyclic import from circuit visualization
        from qiskit.quantum_info.operators.operator import Operator
        return Operator(self.to_matrix())


def to_instruction(self):
        """Convert to Pauli circuit instruction."""
        from qiskit.circuit import QuantumCircuit, QuantumRegister
        from qiskit.extensions.standard import IdGate, XGate, YGate, ZGate
        gates = {'I': IdGate(), 'X': XGate(), 'Y': YGate(), 'Z': ZGate()}
        label = self.to_label()
        n_qubits = self.numberofqubits
        qreg = QuantumRegister(n_qubits)
        circuit = QuantumCircuit(qreg, name='Pauli:{}'.format(label))
        for i, pauli in enumerate(reversed(label)):
            circuit.append(gates[pauli], [qreg[i]])
        return circuit.to_instruction()

def to_instruction ( self ) : from qiskit . circuit import QuantumCircuit , QuantumRegister from qiskit . extensions . standard import IdGate , XGate , YGate , ZGate gates = { 'I' : IdGate ( ) , 'X' : XGate ( ) , 'Y' : YGate ( ) , 'Z' : ZGate ( ) } label = self . to_label ( ) n_qubits = self . numberofqubits qreg = QuantumRegister ( n_qubits ) circuit = QuantumCircuit ( qreg , name = 'Pauli:{}' . format ( label ) ) for i , pauli in enumerate ( reversed ( label ) ) : circuit . append ( gates [ pauli ] , [ qreg [ i ] ] ) return circuit . to_instruction ( )


def update_z(self, z, indices=None):
        """
        Update partial or entire z.

        Args:
            z (numpy.ndarray or list): to-be-updated z
            indices (numpy.ndarray or list or optional): to-be-updated qubit indices

        Returns:
            Pauli: self

        Raises:
            QiskitError: when updating whole z, the number of qubits must be the same.
        """
        z = _make_np_bool(z)
        if indices is None:
            if len(self._z) != len(z):
                raise QiskitError("During updating whole z, you can not "
                                  "change the number of qubits.")
            self._z = z
        else:
            if not isinstance(indices, list) and not isinstance(indices, np.ndarray):
                indices = [indices]
            for p, idx in enumerate(indices):
                self._z[idx] = z[p]

        return self

def
update_z
(
self
,
z
,
indices
=
)
:
z
=
_make_np_bool
(
z
)
if
indices
is
:
if
len
(
self
.
_z
)
!=
len
(
z
)
:
raise
QiskitError
(
"During updating whole z, you can not "
"change the number of qubits."
)
self
.
_z
=
z
else
:
if
not
isinstance
(
indices
,
list
)
and
not
isinstance
(
indices
,
np
.
ndarray
)
:
indices
=
[
indices
]
for
p
,
idx
in
enumerate
(
indices
)
:
self
.
_z
[
idx
]
=
z
[
p
]
return
self


def update_x(self, x, indices=None):
        """
        Update partial or entire x.

        Args:
            x (numpy.ndarray or list): to-be-updated x
            indices (numpy.ndarray or list or optional): to-be-updated qubit indices

        Returns:
            Pauli: self

        Raises:
            QiskitError: when updating whole x, the number of qubits must be the same.
        """
        x = _make_np_bool(x)
        if indices is None:
            if len(self._x) != len(x):
                raise QiskitError("During updating whole x, you can not change "
                                  "the number of qubits.")
            self._x = x
        else:
            if not isinstance(indices, list) and not isinstance(indices, np.ndarray):
                indices = [indices]
            for p, idx in enumerate(indices):
                self._x[idx] = x[p]

        return self


def insert_paulis(self, indices=None, paulis=None, pauli_labels=None):
        """
        Insert or append pauli to the targeted indices.

        If indices is None, it means append at the end.

        Args:
            indices (list[int]): the qubit indices to be inserted
            paulis (Pauli): the to-be-inserted or appended pauli
            pauli_labels (list[str]): the to-be-inserted or appended pauli label

        Note:
            the indices refers to the localion of original paulis,
            e.g. if indices = [0, 2], pauli_labels = ['Z', 'I'] and original pauli = 'ZYXI'
            the pauli will be updated to ZY'I'XI'Z'
            'Z' and 'I' are inserted before the qubit at 0 and 2.

        Returns:
            Pauli: self

        Raises:
            QiskitError: provide both `paulis` and `pauli_labels` at the same time
        """
        if pauli_labels is not None:
            if paulis is not None:
                raise QiskitError("Please only provide either `paulis` or `pauli_labels`")
            if isinstance(pauli_labels, str):
                pauli_labels = list(pauli_labels)
            # since pauli label is in reversed order.
            paulis = Pauli.from_label(pauli_labels[::-1])

        if indices is None:  # append
            self._z = np.concatenate((self._z, paulis.z))
            self._x = np.concatenate((self._x, paulis.x))
        else:
            if not isinstance(indices, list):
                indices = [indices]
            self._z = np.insert(self._z, indices, paulis.z)
            self._x = np.insert(self._x, indices, paulis.x)

        return self

Insert or append pauli to the targeted indices .


def append_paulis(self, paulis=None, pauli_labels=None):
        """
        Append pauli at the end.

        Args:
            paulis (Pauli): the to-be-inserted or appended pauli
            pauli_labels (list[str]): the to-be-inserted or appended pauli label

        Returns:
            Pauli: self
        """
        return self.insert_paulis(None, paulis=paulis, pauli_labels=pauli_labels)

def append_paulis ( self , paulis = None , pauli_labels = None ) : return self . insert_paulis ( None , paulis = paulis , pauli_labels = pauli_labels )


def delete_qubits(self, indices):
        """
        Delete pauli at the indices.

        Args:
            indices(list[int]): the indices of to-be-deleted paulis

        Returns:
            Pauli: self
        """
        if not isinstance(indices, list):
            indices = [indices]

        self._z = np.delete(self._z, indices)
        self._x = np.delete(self._x, indices)

        return self

def delete_qubits ( self , indices ) : if not isinstance ( indices , list ) : indices = [ indices ] self . _z = np . delete ( self . _z , indices ) self . _x = np . delete ( self . _x , indices ) return self


def random(cls, num_qubits, seed=None):
        """Return a random Pauli on number of qubits.

        Args:
            num_qubits (int): the number of qubits
            seed (int): Optional. To set a random seed.
        Returns:
            Pauli: the random pauli
        """
        if seed is not None:
            np.random.seed(seed)
        z = np.random.randint(2, size=num_qubits).astype(np.bool)
        x = np.random.randint(2, size=num_qubits).astype(np.bool)
        return cls(z, x)

def random ( cls , num_qubits , seed = None ) : if seed is not None : np . random . seed ( seed ) z = np . random . randint ( 2 , size = num_qubits ) . astype ( np . bool ) x = np . random . randint ( 2 , size = num_qubits ) . astype ( np . bool ) return cls ( z , x )

Return a random Pauli on number of qubits .


def pauli_single(cls, num_qubits, index, pauli_label):
        """
        Generate single qubit pauli at index with pauli_label with length num_qubits.

        Args:
            num_qubits (int): the length of pauli
            index (int): the qubit index to insert the single qubii
            pauli_label (str): pauli

        Returns:
            Pauli: single qubit pauli
        """
        tmp = Pauli.from_label(pauli_label)
        z = np.zeros(num_qubits, dtype=np.bool)
        x = np.zeros(num_qubits, dtype=np.bool)

        z[index] = tmp.z[0]
        x[index] = tmp.x[0]

        return cls(z, x)

def pauli_single ( cls , num_qubits , index , pauli_label ) : tmp = Pauli . from_label ( pauli_label ) z = np . zeros ( num_qubits , dtype = np . bool ) x = np . zeros ( num_qubits , dtype = np . bool ) z [ index ] = tmp . z [ 0 ] x [ index ] = tmp . x [ 0 ] return cls ( z , x )

Generate single qubit pauli at index with pauli_label with length num_qubits .


def _get_measure_outcome(self, qubit):
        """Simulate the outcome of measurement of a qubit.

        Args:
            qubit (int): the qubit to measure

        Return:
            tuple: pair (outcome, probability) where outcome is '0' or '1' and
            probability is the probability of the returned outcome.
        """
        # Axis for numpy.sum to compute probabilities
        axis = list(range(self._number_of_qubits))
        axis.remove(self._number_of_qubits - 1 - qubit)
        probabilities = np.sum(np.abs(self._statevector) ** 2, axis=tuple(axis))
        # Compute einsum index string for 1-qubit matrix multiplication
        random_number = self._local_random.rand()
        if random_number < probabilities[0]:
            return '0', probabilities[0]
        # Else outcome was '1'
        return '1', probabilities[1]

Simulate the outcome of measurement of a qubit .


def _add_sample_measure(self, measure_params, num_samples):
        """Generate memory samples from current statevector.

        Args:
            measure_params (list): List of (qubit, cmembit) values for
                                   measure instructions to sample.
            num_samples (int): The number of memory samples to generate.

        Returns:
            list: A list of memory values in hex format.
        """
        # Get unique qubits that are actually measured
        measured_qubits = list({qubit for qubit, cmembit in measure_params})
        num_measured = len(measured_qubits)
        # Axis for numpy.sum to compute probabilities
        axis = list(range(self._number_of_qubits))
        for qubit in reversed(measured_qubits):
            # Remove from largest qubit to smallest so list position is correct
            # with respect to position from end of the list
            axis.remove(self._number_of_qubits - 1 - qubit)
        probabilities = np.reshape(np.sum(np.abs(self._statevector) ** 2,
                                          axis=tuple(axis)),
                                   2 ** num_measured)
        # Generate samples on measured qubits
        samples = self._local_random.choice(range(2 ** num_measured),
                                            num_samples, p=probabilities)
        # Convert to bit-strings
        memory = []
        for sample in samples:
            classical_memory = self._classical_memory
            for count, (qubit, cmembit) in enumerate(sorted(measure_params)):
                qubit_outcome = int((sample & (1 << count)) >> count)
                membit = 1 << cmembit
                classical_memory = (classical_memory & (~membit)) | (qubit_outcome << cmembit)
            value = bin(classical_memory)[2:]
            memory.append(hex(int(value, 2)))
        return memory

Generate memory samples from current statevector .


def _add_qasm_measure(self, qubit, cmembit, cregbit=None):
        """Apply a measure instruction to a qubit.

        Args:
            qubit (int): qubit is the qubit measured.
            cmembit (int): is the classical memory bit to store outcome in.
            cregbit (int, optional): is the classical register bit to store outcome in.
        """
        # get measure outcome
        outcome, probability = self._get_measure_outcome(qubit)
        # update classical state
        membit = 1 << cmembit
        self._classical_memory = (self._classical_memory & (~membit)) | (int(outcome) << cmembit)

        if cregbit is not None:
            regbit = 1 << cregbit
            self._classical_register = \
                (self._classical_register & (~regbit)) | (int(outcome) << cregbit)

        # update quantum state
        if outcome == '0':
            update_diag = [[1 / np.sqrt(probability), 0], [0, 0]]
        else:
            update_diag = [[0, 0], [0, 1 / np.sqrt(probability)]]
        # update classical state
        self._add_unitary_single(update_diag, qubit)

def
_add_qasm_measure
(
self
,
qubit
,
cmembit
,
cregbit
=
)
:
# get measure outcome
outcome
,
probability
=
self
.
_get_measure_outcome
(
qubit
)
# update classical state
membit
=
1
<<
cmembit
self
.
_classical_memory
=
(
self
.
_classical_memory
&
(
~
membit
)
)
|
(
int
(
outcome
)
<<
cmembit
)
if
cregbit
is
not
:
regbit
=
1
<<
cregbit
self
.
_classical_register
=
(
self
.
_classical_register
&
(
~
regbit
)
)
|
(
int
(
outcome
)
<<
cregbit
)
# update quantum state
if
outcome
==
'0'
:
update_diag
=
[
[
1
/
np
.
sqrt
(
probability
)
,
0
]
,
[
0
,
0
]
]
else
:
update_diag
=
[
[
0
,
0
]
,
[
0
,
1
/
np
.
sqrt
(
probability
)
]
]
# update classical state
self
.
_add_unitary_single
(
update_diag
,
qubit
)

Apply a measure instruction to a qubit .


def _add_qasm_reset(self, qubit):
        """Apply a reset instruction to a qubit.

        Args:
            qubit (int): the qubit being rest

        This is done by doing a simulating a measurement
        outcome and projecting onto the outcome state while
        renormalizing.
        """
        # get measure outcome
        outcome, probability = self._get_measure_outcome(qubit)
        # update quantum state
        if outcome == '0':
            update = [[1 / np.sqrt(probability), 0], [0, 0]]
            self._add_unitary_single(update, qubit)
        else:
            update = [[0, 1 / np.sqrt(probability)], [0, 0]]
            self._add_unitary_single(update, qubit)

def
_add_qasm_reset
(
self
,
qubit
)
:
# get measure outcome
outcome
,
probability
=
self
.
_get_measure_outcome
(
qubit
)
# update quantum state
if
outcome
==
'0'
:
update
=
[
[
1
/
np
.
sqrt
(
probability
)
,
0
]
,
[
0
,
0
]
]
self
.
_add_unitary_single
(
update
,
qubit
)
else
:
update
=
[
[
0
,
1
/
np
.
sqrt
(
probability
)
]
,
[
0
,
0
]
]
self
.
_add_unitary_single
(
update
,
qubit
)


def _validate_initial_statevector(self):
        """Validate an initial statevector"""
        # If initial statevector isn't set we don't need to validate
        if self._initial_statevector is None:
            return
        # Check statevector is correct length for number of qubits
        length = len(self._initial_statevector)
        required_dim = 2 ** self._number_of_qubits
        if length != required_dim:
            raise BasicAerError('initial statevector is incorrect length: ' +
                                '{} != {}'.format(length, required_dim))


def _initialize_statevector(self):
        """Set the initial statevector for simulation"""
        if self._initial_statevector is None:
            # Set to default state of all qubits in |0>
            self._statevector = np.zeros(2 ** self._number_of_qubits,
                                         dtype=complex)
            self._statevector[0] = 1
        else:
            self._statevector = self._initial_statevector.copy()
        # Reshape to rank-N tensor
        self._statevector = np.reshape(self._statevector,
                                       self._number_of_qubits * [2])


def _get_statevector(self):
        """Return the current statevector in JSON Result spec format"""
        vec = np.reshape(self._statevector, 2 ** self._number_of_qubits)
        # Expand complex numbers
        vec = np.stack([vec.real, vec.imag], axis=1)
        # Truncate small values
        vec[abs(vec) < self._chop_threshold] = 0.0
        return vec

def
_get_statevector
(
self
)
:
vec
=
np
.
reshape
(
self
.
_statevector
,
2
**
self
.
_number_of_qubits
)
# Expand complex numbers
vec
=
np
.
stack
(
[
vec
.
real
,
vec
.
imag
]
,
axis
=
1
)
# Truncate small values
vec
[
abs
(
vec
)
<
self
.
_chop_threshold
]
=
0.0
return
vec


def _validate_measure_sampling(self, experiment):
        """Determine if measure sampling is allowed for an experiment

        Args:
            experiment (QobjExperiment): a qobj experiment.
        """
        # If shots=1 we should disable measure sampling.
        # This is also required for statevector simulator to return the
        # correct final statevector without silently dropping final measurements.
        if self._shots <= 1:
            self._sample_measure = False
            return

        # Check for config flag
        if hasattr(experiment.config, 'allows_measure_sampling'):
            self._sample_measure = experiment.config.allows_measure_sampling
        # If flag isn't found do a simple test to see if a circuit contains
        # no reset instructions, and no gates instructions after
        # the first measure.
        else:
            measure_flag = False
            for instruction in experiment.instructions:
                # If circuit contains reset operations we cannot sample
                if instruction.name == "reset":
                    self._sample_measure = False
                    return
                # If circuit contains a measure option then we can
                # sample only if all following operations are measures
                if measure_flag:
                    # If we find a non-measure instruction
                    # we cannot do measure sampling
                    if instruction.name not in ["measure", "barrier", "id", "u0"]:
                        self._sample_measure = False
                        return
                elif instruction.name == "measure":
                    measure_flag = True
            # If we made it to the end of the circuit without returning
            # measure sampling is allowed
            self._sample_measure = True


def run(self, qobj, backend_options=None):
        """Run qobj asynchronously.

        Args:
            qobj (Qobj): payload of the experiment
            backend_options (dict): backend options

        Returns:
            BasicAerJob: derived from BaseJob

        Additional Information:
            backend_options: Is a dict of options for the backend. It may contain
                * "initial_statevector": vector_like

            The "initial_statevector" option specifies a custom initial
            initial statevector for the simulator to be used instead of the all
            zero state. This size of this vector must be correct for the number
            of qubits in all experiments in the qobj.

            Example::

                backend_options = {
                    "initial_statevector": np.array([1, 0, 0, 1j]) / np.sqrt(2),
                }
        """
        self._set_options(qobj_config=qobj.config,
                          backend_options=backend_options)
        job_id = str(uuid.uuid4())
        job = BasicAerJob(self, job_id, self._run_job, qobj)
        job.submit()
        return job

def run ( self , qobj , backend_options = None ) : self . _set_options ( qobj_config = qobj . config , backend_options = backend_options ) job_id = str ( uuid . uuid4 ( ) ) job = BasicAerJob ( self , job_id , self . _run_job , qobj ) job . submit ( ) return job


def _run_job(self, job_id, qobj):
        """Run experiments in qobj

        Args:
            job_id (str): unique id for the job.
            qobj (Qobj): job description

        Returns:
            Result: Result object
        """
        self._validate(qobj)
        result_list = []
        self._shots = qobj.config.shots
        self._memory = getattr(qobj.config, 'memory', False)
        self._qobj_config = qobj.config
        start = time.time()
        for experiment in qobj.experiments:
            result_list.append(self.run_experiment(experiment))
        end = time.time()
        result = {'backend_name': self.name(),
                  'backend_version': self._configuration.backend_version,
                  'qobj_id': qobj.qobj_id,
                  'job_id': job_id,
                  'results': result_list,
                  'status': 'COMPLETED',
                  'success': True,
                  'time_taken': (end - start),
                  'header': qobj.header.as_dict()}

        return Result.from_dict(result)

def _run_job ( self , job_id , qobj ) : self . _validate ( qobj ) result_list = [ ] self . _shots = qobj . config . shots self . _memory = getattr ( qobj . config , 'memory' , False ) self . _qobj_config = qobj . config start = time . time ( ) for experiment in qobj . experiments : result_list . append ( self . run_experiment ( experiment ) ) end = time . time ( ) result = { 'backend_name' : self . name ( ) , 'backend_version' : self . _configuration . backend_version , 'qobj_id' : qobj . qobj_id , 'job_id' : job_id , 'results' : result_list , 'status' : 'COMPLETED' , 'success' : True , 'time_taken' : ( end - start ) , 'header' : qobj . header . as_dict ( ) } return Result . from_dict ( result )


def _validate(self, qobj):
        """Semantic validations of the qobj which cannot be done via schemas."""
        n_qubits = qobj.config.n_qubits
        max_qubits = self.configuration().n_qubits
        if n_qubits > max_qubits:
            raise BasicAerError('Number of qubits {} '.format(n_qubits) +
                                'is greater than maximum ({}) '.format(max_qubits) +
                                'for "{}".'.format(self.name()))
        for experiment in qobj.experiments:
            name = experiment.header.name
            if experiment.config.memory_slots == 0:
                logger.warning('No classical registers in circuit "%s", '
                               'counts will be empty.', name)
            elif 'measure' not in [op.name for op in experiment.instructions]:
                logger.warning('No measurements in circuit "%s", '
                               'classical register will remain all zeros.', name)

Semantic validations of the qobj which cannot be done via schemas .


def _validate_initial_unitary(self):
        """Validate an initial unitary matrix"""
        # If initial unitary isn't set we don't need to validate
        if self._initial_unitary is None:
            return
        # Check unitary is correct length for number of qubits
        shape = np.shape(self._initial_unitary)
        required_shape = (2 ** self._number_of_qubits,
                          2 ** self._number_of_qubits)
        if shape != required_shape:
            raise BasicAerError('initial unitary is incorrect shape: ' +
                                '{} != 2 ** {}'.format(shape, required_shape))


def _initialize_unitary(self):
        """Set the initial unitary for simulation"""
        self._validate_initial_unitary()
        if self._initial_unitary is None:
            # Set to identity matrix
            self._unitary = np.eye(2 ** self._number_of_qubits,
                                   dtype=complex)
        else:
            self._unitary = self._initial_unitary.copy()
        # Reshape to rank-N tensor
        self._unitary = np.reshape(self._unitary,
                                   self._number_of_qubits * [2, 2])

def
_initialize_unitary
(
self
)
:
self
.
_validate_initial_unitary
(
)
if
self
.
_initial_unitary
is
:
# Set to identity matrix
self
.
_unitary
=
np
.
eye
(
2
**
self
.
_number_of_qubits
,
dtype
=
complex
)
else
:
self
.
_unitary
=
self
.
_initial_unitary
.
copy
(
)
# Reshape to rank-N tensor
self
.
_unitary
=
np
.
reshape
(
self
.
_unitary
,
self
.
_number_of_qubits
*
[
2
,
2
]
)


def _get_unitary(self):
        """Return the current unitary in JSON Result spec format"""
        unitary = np.reshape(self._unitary, 2 * [2 ** self._number_of_qubits])
        # Expand complex numbers
        unitary = np.stack((unitary.real, unitary.imag), axis=-1)
        # Truncate small values
        unitary[abs(unitary) < self._chop_threshold] = 0.0
        return unitary

def
_get_unitary
(
self
)
:
unitary
=
np
.
reshape
(
self
.
_unitary
,
2
*
[
2
**
self
.
_number_of_qubits
]
)
# Expand complex numbers
unitary
=
np
.
stack
(
(
unitary
.
real
,
unitary
.
imag
)
,
axis
=
1
)
# Truncate small values
unitary
[
abs
(
unitary
)
<
self
.
_chop_threshold
]
=
0.0
return
unitary


def _run_job(self, job_id, qobj):
        """Run experiments in qobj.

        Args:
            job_id (str): unique id for the job.
            qobj (Qobj): job description

        Returns:
            Result: Result object
        """
        self._validate(qobj)
        result_list = []
        start = time.time()
        for experiment in qobj.experiments:
            result_list.append(self.run_experiment(experiment))
        end = time.time()
        result = {'backend_name': self.name(),
                  'backend_version': self._configuration.backend_version,
                  'qobj_id': qobj.qobj_id,
                  'job_id': job_id,
                  'results': result_list,
                  'status': 'COMPLETED',
                  'success': True,
                  'time_taken': (end - start),
                  'header': qobj.header.as_dict()}

        return Result.from_dict(result)

def _run_job ( self , job_id , qobj ) : self . _validate ( qobj ) result_list = [ ] start = time . time ( ) for experiment in qobj . experiments : result_list . append ( self . run_experiment ( experiment ) ) end = time . time ( ) result = { 'backend_name' : self . name ( ) , 'backend_version' : self . _configuration . backend_version , 'qobj_id' : qobj . qobj_id , 'job_id' : job_id , 'results' : result_list , 'status' : 'COMPLETED' , 'success' : True , 'time_taken' : ( end - start ) , 'header' : qobj . header . as_dict ( ) } return Result . from_dict ( result )


def _validate(self, qobj):
        """Semantic validations of the qobj which cannot be done via schemas.
        Some of these may later move to backend schemas.
        1. No shots
        2. No measurements in the middle
        """
        n_qubits = qobj.config.n_qubits
        max_qubits = self.configuration().n_qubits
        if n_qubits > max_qubits:
            raise BasicAerError('Number of qubits {} '.format(n_qubits) +
                                'is greater than maximum ({}) '.format(max_qubits) +
                                'for "{}".'.format(self.name()))
        if hasattr(qobj.config, 'shots') and qobj.config.shots != 1:
            logger.info('"%s" only supports 1 shot. Setting shots=1.',
                        self.name())
            qobj.config.shots = 1
        for experiment in qobj.experiments:
            name = experiment.header.name
            if getattr(experiment.config, 'shots', 1) != 1:
                logger.info('"%s" only supports 1 shot. '
                            'Setting shots=1 for circuit "%s".',
                            self.name(), name)
                experiment.config.shots = 1
            for operation in experiment.instructions:
                if operation.name in ['measure', 'reset']:
                    raise BasicAerError('Unsupported "%s" instruction "%s" ' +
                                        'in circuit "%s" ', self.name(),
                                        operation.name, name)

Semantic validations of the qobj which cannot be done via schemas . Some of these may later move to backend schemas . 1 . No shots 2 . No measurements in the middle


def _is_bit(obj):
    """Determine if obj is a bit"""
    # If there is a bit type this could be replaced by isinstance.
    if isinstance(obj, tuple) and len(obj) == 2:
        if isinstance(obj[0], Register) and isinstance(obj[1], int) and obj[1] < len(obj[0]):
            return True
    return False


def run(self, dag):
        """
        Pick a layout by assigning n circuit qubits to device qubits 0, .., n-1.

        Args:
            dag (DAGCircuit): DAG to find layout for.

        Raises:
            TranspilerError: if dag wider than self.coupling_map
        """
        num_dag_qubits = sum([qreg.size for qreg in dag.qregs.values()])
        if num_dag_qubits > self.coupling_map.size():
            raise TranspilerError('Number of qubits greater than device.')
        self.property_set['layout'] = Layout.generate_trivial_layout(*dag.qregs.values())

def
run
(
self
,
dag
)
:
num_dag_qubits
=
sum
(
[
qreg
.
size
for
qreg
in
dag
.
qregs
.
values
(
)
]
)
if
num_dag_qubits
>
self
.
coupling_map
.
size
(
)
:
raise
TranspilerError
(
'Number of qubits greater than device.'
)
self
.
property_set
[
'layout'
]
=
Layout
.
generate_trivial_layout
(
*
dag
.
qregs
.
values
(
)
)

Pick a layout by assigning n circuit qubits to device qubits 0 .. n - 1 .


def has_overlap(self, interval: 'Interval') -> bool:
        """Check if self has overlap with `interval`.

        Args:
            interval: interval to be examined

        Returns:
            bool: True if self has overlap with `interval` otherwise False
        """
        if self.begin < interval.end and interval.begin < self.end:
            return True
        return False

def has_overlap ( self , interval : 'Interval' ) -> bool : if self . begin < interval . end and interval . begin < self . end : return True return False

Check if self has overlap with interval .


def shift(self, time: int) -> 'Interval':
        """Return a new interval shifted by `time` from self

        Args:
            time: time to be shifted

        Returns:
            Interval: interval shifted by `time`
        """
        return Interval(self._begin + time, self._end + time)

def shift ( self , time : int ) -> 'Interval' : return Interval ( self . _begin + time , self . _end + time )

Return a new interval shifted by time from self


def shift(self, time: int) -> 'Timeslot':
        """Return a new Timeslot shifted by `time`.

        Args:
            time: time to be shifted
        """
        return Timeslot(self.interval.shift(time), self.channel)

def shift ( self , time : int ) -> 'Timeslot' : return Timeslot ( self . interval . shift ( time ) , self . channel )


def ch_start_time(self, *channels: List[Channel]) -> int:
        """Return earliest start time in this collection.

        Args:
            *channels: Channels over which to obtain start_time.
        """
        intervals = list(itertools.chain(*(self._table[chan] for chan in channels
                                           if chan in self._table)))
        if intervals:
            return min((interval.begin for interval in intervals))
        return 0

def ch_start_time ( self , * channels : List [ Channel ] ) -> int : intervals = list ( itertools . chain ( * ( self . _table [ chan ] for chan in channels if chan in self . _table ) ) ) if intervals : return min ( ( interval . begin for interval in intervals ) ) return 0

Return earliest start time in this collection .


def ch_stop_time(self, *channels: List[Channel]) -> int:
        """Return maximum time of timeslots over all channels.

        Args:
            *channels: Channels over which to obtain stop time.
        """
        intervals = list(itertools.chain(*(self._table[chan] for chan in channels
                                           if chan in self._table)))
        if intervals:
            return max((interval.end for interval in intervals))
        return 0

def ch_stop_time ( self , * channels : List [ Channel ] ) -> int : intervals = list ( itertools . chain ( * ( self . _table [ chan ] for chan in channels if chan in self . _table ) ) ) if intervals : return max ( ( interval . end for interval in intervals ) ) return 0

Return maximum time of timeslots over all channels .


def is_mergeable_with(self, timeslots: 'TimeslotCollection') -> bool:
        """Return if self is mergeable with `timeslots`.

        Args:
            timeslots: TimeslotCollection to be checked
        """
        for slot in timeslots.timeslots:
            for interval in self._table[slot.channel]:
                if slot.interval.has_overlap(interval):
                    return False
        return True

def is_mergeable_with ( self , timeslots : 'TimeslotCollection' ) -> bool : for slot in timeslots . timeslots : for interval in self . _table [ slot . channel ] : if slot . interval . has_overlap ( interval ) : return False return True

Return if self is mergeable with timeslots .


def merged(self, timeslots: 'TimeslotCollection') -> 'TimeslotCollection':
        """Return a new TimeslotCollection merged with a specified `timeslots`

        Args:
            timeslots: TimeslotCollection to be merged
        """
        slots = [Timeslot(slot.interval, slot.channel) for slot in self.timeslots]
        slots.extend([Timeslot(slot.interval, slot.channel) for slot in timeslots.timeslots])
        return TimeslotCollection(*slots)

def merged ( self , timeslots : 'TimeslotCollection' ) -> 'TimeslotCollection' : slots = [ Timeslot ( slot . interval , slot . channel ) for slot in self . timeslots ] slots . extend ( [ Timeslot ( slot . interval , slot . channel ) for slot in timeslots . timeslots ] ) return TimeslotCollection ( * slots )

Return a new TimeslotCollection merged with a specified timeslots


def shift(self, time: int) -> 'TimeslotCollection':
        """Return a new TimeslotCollection shifted by `time`.

        Args:
            time: time to be shifted by
        """
        slots = [Timeslot(slot.interval.shift(time), slot.channel) for slot in self.timeslots]
        return TimeslotCollection(*slots)

def shift ( self , time : int ) -> 'TimeslotCollection' : slots = [ Timeslot ( slot . interval . shift ( time ) , slot . channel ) for slot in self . timeslots ] return TimeslotCollection ( * slots )

Return a new TimeslotCollection shifted by time .


def report(self, branch, commit, infourl=None):
        """Report on GitHub that the specified branch is failing to build at
        the specified commit. The method will open an issue indicating that
        the branch is failing. If there is an issue already open, it will add a
        comment avoiding to report twice about the same failure.

        Args:
            branch (str): branch name to report about.
            commit (str): commit hash at which the build fails.
            infourl (str): URL with extra info about the failure such as the
                build logs.
        """
        issue_number = self._get_report_issue_number()
        if issue_number:
            self._report_as_comment(issue_number, branch, commit, infourl)
        else:
            self._report_as_issue(branch, commit, infourl)

def report ( self , branch , commit , infourl = None ) : issue_number = self . _get_report_issue_number ( ) if issue_number : self . _report_as_comment ( issue_number , branch , commit , infourl ) else : self . _report_as_issue ( branch , commit , infourl )

Report on GitHub that the specified branch is failing to build at the specified commit . The method will open an issue indicating that the branch is failing . If there is an issue already open it will add a comment avoiding to report twice about the same failure .


def process_data(rho):
    """ Sort rho data """
    result = dict()

    num = int(np.log2(len(rho)))
    labels = list(map(lambda x: x.to_label(), pauli_group(num)))
    values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),
                      pauli_group(num)))

    for position, label in enumerate(labels):
        result[label] = values[position]
    return result

def process_data ( rho ) : result = dict ( ) num = int ( np . log2 ( len ( rho ) ) ) labels = list ( map ( lambda x : x . to_label ( ) , pauli_group ( num ) ) ) values = list ( map ( lambda x : np . real ( np . trace ( np . dot ( x . to_matrix ( ) , rho ) ) ) , pauli_group ( num ) ) ) for position , label in enumerate ( labels ) : result [ label ] = values [ position ] return result


def iplot_state_paulivec(rho, figsize=None, slider=False, show_legend=False):
    """ Create a paulivec representation.

        Graphical representation of the input array.

        Args:
            rho (array): State vector or density matrix.
            figsize (tuple): Figure size in pixels.
            slider (bool): activate slider
            show_legend (bool): show legend of graph content
    """

    # HTML
    html_template = Template("""

    """)

    # JavaScript
    javascript_template = Template("""

    """)
    rho = _validate_input_state(rho)
    # set default figure size if none given
    if figsize is None:
        figsize = (7, 5)

    options = {'width': figsize[0], 'height': figsize[1],
               'slider': int(slider), 'show_legend': int(show_legend)}

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

    data_to_plot = []
    rho_data = process_data(rho)
    data_to_plot.append(dict(
        data=rho_data
    ))

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

    javascript = javascript_template.substitute({
        'divNumber': div_number,
        'executions': data_to_plot,
        'options': options
    })

    display(HTML(html + javascript))

"""
    <script>
        requirejs.config({
            paths: {
                qVisualization: "https://qvisualization.mybluemix.net/q-visualizations"
            }
        });

        require(["qVisualization"], function(qVisualizations) {
            qVisualizations.plotState("paulivec_$divNumber",
                                      "paulivec",
                                      $executions,
                                      $options);
        });
    </script>
    """


def rzz(self, theta, qubit1, qubit2):
    """Apply RZZ to circuit."""
    return self.append(RZZGate(theta), [qubit1, qubit2], [])

def rzz ( self , theta , qubit1 , qubit2 ) : return self . append ( RZZGate ( theta ) , [ qubit1 , qubit2 ] , [ ] )


def cswap(self, ctl, tgt1, tgt2):
    """Apply Fredkin to circuit."""
    return self.append(FredkinGate(), [ctl, tgt1, tgt2], [])

def cswap ( self , ctl , tgt1 , tgt2 ) : return self . append ( FredkinGate ( ) , [ ctl , tgt1 , tgt2 ] , [ ] )


def _initialize_backend_prop(self):
        """
        Extract readout and CNOT errors and compute swap costs.
        """
        backend_prop = self.backend_prop
        for ginfo in backend_prop.gates:
            if ginfo.gate == 'cx':
                for item in ginfo.parameters:
                    if item.name == 'gate_error':
                        g_reliab = 1.0 - item.value
                        break
                    else:
                        g_reliab = 1.0
                swap_reliab = -math.log(pow(g_reliab, 3))
                self.swap_graph.add_edge(ginfo.qubits[0], ginfo.qubits[1], weight=swap_reliab)
                self.swap_graph.add_edge(ginfo.qubits[1], ginfo.qubits[0], weight=swap_reliab)
                self.cx_errors[(ginfo.qubits[0], ginfo.qubits[1])] = g_reliab
                self.gate_list.append((ginfo.qubits[0], ginfo.qubits[1]))
        idx = 0
        for q in backend_prop.qubits:
            for nduv in q:
                if nduv.name == 'readout_error':
                    self.readout_errors[idx] = 1.0 - nduv.value
                    self.available_hw_qubits.append(idx)
            idx += 1
        for edge in self.cx_errors:
            self.gate_cost[edge] = self.cx_errors[edge] * self.readout_errors[edge[0]] *\
                self.readout_errors[edge[1]]
        self.swap_paths, swap_costs_temp = nx.algorithms.shortest_paths.dense.\
            floyd_warshall_predecessor_and_distance(self.swap_graph, weight='weight')
        for i in swap_costs_temp:
            self.swap_costs[i] = {}
            for j in swap_costs_temp[i]:
                if (i, j) in self.cx_errors:
                    self.swap_costs[i][j] = self.cx_errors[(i, j)]
                elif (j, i) in self.cx_errors:
                    self.swap_costs[i][j] = self.cx_errors[(j, i)]
                else:
                    best_reliab = 0.0
                    for n in self.swap_graph.neighbors(j):
                        if (n, j) in self.cx_errors:
                            reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(n, j)]
                        else:
                            reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(j, n)]
                        if reliab > best_reliab:
                            best_reliab = reliab
                    self.swap_costs[i][j] = best_reliab

def _initialize_backend_prop ( self ) : backend_prop = self . backend_prop for ginfo in backend_prop . gates : if ginfo . gate == 'cx' : for item in ginfo . parameters : if item . name == 'gate_error' : g_reliab = 1.0 - item . value break else : g_reliab = 1.0 swap_reliab = - math . log ( pow ( g_reliab , 3 ) ) self . swap_graph . add_edge ( ginfo . qubits [ 0 ] , ginfo . qubits [ 1 ] , weight = swap_reliab ) self . swap_graph . add_edge ( ginfo . qubits [ 1 ] , ginfo . qubits [ 0 ] , weight = swap_reliab ) self . cx_errors [ ( ginfo . qubits [ 0 ] , ginfo . qubits [ 1 ] ) ] = g_reliab self . gate_list . append ( ( ginfo . qubits [ 0 ] , ginfo . qubits [ 1 ] ) ) idx = 0 for q in backend_prop . qubits : for nduv in q : if nduv . name == 'readout_error' : self . readout_errors [ idx ] = 1.0 - nduv . value self . available_hw_qubits . append ( idx ) idx += 1 for edge in self . cx_errors : self . gate_cost [ edge ] = self . cx_errors [ edge ] * self . readout_errors [ edge [ 0 ] ] * self . readout_errors [ edge [ 1 ] ] self . swap_paths , swap_costs_temp = nx . algorithms . shortest_paths . dense . floyd_warshall_predecessor_and_distance ( self . swap_graph , weight = 'weight' ) for i in swap_costs_temp : self . swap_costs [ i ] = { } for j in swap_costs_temp [ i ] : if ( i , j ) in self . cx_errors : self . swap_costs [ i ] [ j ] = self . cx_errors [ ( i , j ) ] elif ( j , i ) in self . cx_errors : self . swap_costs [ i ] [ j ] = self . cx_errors [ ( j , i ) ] else : best_reliab = 0.0 for n in self . swap_graph . neighbors ( j ) : if ( n , j ) in self . cx_errors : reliab = math . exp ( - swap_costs_temp [ i ] [ n ] ) * self . cx_errors [ ( n , j ) ] else : reliab = math . exp ( - swap_costs_temp [ i ] [ n ] ) * self . cx_errors [ ( j , n ) ] if reliab > best_reliab : best_reliab = reliab self . swap_costs [ i ] [ j ] = best_reliab

Extract readout and CNOT errors and compute swap costs .