qiskit/mapper/_mapping.py
def swap_mapper(circuit_graph, coupling_graph,
                initial_layout=None,
                basis="cx,u1,u2,u3,id", trials=20, seed=None):
    """Map a DAGCircuit onto a CouplingGraph using swap gates.

    Args:
        circuit_graph (DAGCircuit): input DAG circuit
        coupling_graph (CouplingGraph): coupling graph to map onto
        initial_layout (dict): dict from qubits of circuit_graph to qubits
            of coupling_graph (optional)
        basis (str): basis string specifying basis of output DAGCircuit
        trials (int): number of trials.
        seed (int): initial seed.

    Returns:
        DAGCircuit: object containing a circuit equivalent to
        circuit_graph that respects couplings in coupling_graph, and
        a layout dict mapping qubits of circuit_graph into qubits
        of coupling_graph. The layout may differ from the initial_layout
        if the first layer of gates cannot be executed on the
        initial_layout. Finally, returned is the final layer qubit
        permutation that is needed to add measurements back in.

    Raises:
        MapperError: if there was any error during the mapping or with the
            parameters.
    """
    if circuit_graph.width() > coupling_graph.size():
        raise MapperError("Not enough qubits in CouplingGraph")

    # Schedule the input circuit
    layerlist = list(circuit_graph.layers())
    logger.debug("schedule:")
    for i, v in enumerate(layerlist):
        logger.debug("    %d: %s", i, v["partition"])

    if initial_layout is not None:
        # Check the input layout
        circ_qubits = circuit_graph.get_qubits()
        coup_qubits = coupling_graph.get_qubits()
        qubit_subset = []
        for k, v in initial_layout.items():
            qubit_subset.append(v)
            if k not in circ_qubits:
                raise MapperError("initial_layout qubit %s[%d] not in input "
                                  "DAGCircuit" % (k[0], k[1]))
            if v not in coup_qubits:
                raise MapperError("initial_layout qubit %s[%d] not in input "
                                  "CouplingGraph" % (v[0], v[1]))
    else:
        # Supply a default layout
        qubit_subset = coupling_graph.get_qubits()
        qubit_subset = qubit_subset[0:circuit_graph.width()]
        initial_layout = {a: b for a, b in
                          zip(circuit_graph.get_qubits(), qubit_subset)}

    # Find swap circuit to preceed to each layer of input circuit
    layout = initial_layout.copy()
    layout_max_index = max(map(lambda x: x[1]+1, layout.values()))

    # Construct an empty DAGCircuit with one qreg "q"
    # and the same set of cregs as the input circuit
    dagcircuit_output = DAGCircuit()
    dagcircuit_output.name = circuit_graph.name
    dagcircuit_output.add_qreg("q", layout_max_index)
    for name, size in circuit_graph.cregs.items():
        dagcircuit_output.add_creg(name, size)

    # Make a trivial wire mapping between the subcircuits
    # returned by swap_mapper_layer_update and the circuit
    # we are building
    identity_wire_map = {}
    for j in range(layout_max_index):
        identity_wire_map[("q", j)] = ("q", j)
    for name, size in circuit_graph.cregs.items():
        for j in range(size):
            identity_wire_map[(name, j)] = (name, j)

    first_layer = True  # True until first layer is output
    logger.debug("initial_layout = %s", layout)

    # Iterate over layers
    for i, layer in enumerate(layerlist):

        # Attempt to find a permutation for this layer
        success_flag, best_circ, best_d, best_layout, trivial_flag \
            = layer_permutation(layer["partition"], layout,
                                qubit_subset, coupling_graph, trials, seed)
        logger.debug("swap_mapper: layer %d", i)
        logger.debug("swap_mapper: success_flag=%s,best_d=%s,trivial_flag=%s",
                     success_flag, str(best_d), trivial_flag)

        # If this fails, try one gate at a time in this layer
        if not success_flag:
            logger.debug("swap_mapper: failed, layer %d, "
                         "retrying sequentially", i)
            serial_layerlist = list(layer["graph"].serial_layers())

            # Go through each gate in the layer
            for j, serial_layer in enumerate(serial_layerlist):

                success_flag, best_circ, best_d, best_layout, trivial_flag \
                    = layer_permutation(serial_layer["partition"],
                                        layout, qubit_subset, coupling_graph,
                                        trials, seed)
                logger.debug("swap_mapper: layer %d, sublayer %d", i, j)
                logger.debug("swap_mapper: success_flag=%s,best_d=%s,"
                             "trivial_flag=%s",
                             success_flag, str(best_d), trivial_flag)

                # Give up if we fail again
                if not success_flag:
                    raise MapperError("swap_mapper failed: " +
                                      "layer %d, sublayer %d" % (i, j) +
                                      ", \"%s\"" %
                                      serial_layer["graph"].qasm(
                                          no_decls=True,
                                          aliases=layout))

                # If this layer is only single-qubit gates,
                # and we have yet to see multi-qubit gates,
                # continue to the next inner iteration
                if trivial_flag and first_layer:
                    logger.debug("swap_mapper: skip to next sublayer")
                    continue

                # Update the record of qubit positions for each inner iteration
                layout = best_layout
                # Update the QASM
                dagcircuit_output.compose_back(
                    swap_mapper_layer_update(j,
                                             first_layer,
                                             best_layout,
                                             best_d,
                                             best_circ,
                                             serial_layerlist),
                    identity_wire_map)
                # Update initial layout
                if first_layer:
                    initial_layout = layout
                    first_layer = False

        else:
            # Update the record of qubit positions for each iteration
            layout = best_layout

            # Update the QASM
            dagcircuit_output.compose_back(
                swap_mapper_layer_update(i,
                                         first_layer,
                                         best_layout,
                                         best_d,
                                         best_circ,
                                         layerlist),
                identity_wire_map)
            # Update initial layout
            if first_layer:
                initial_layout = layout
                first_layer = False

    # This is the final layout that we need to correctly replace
    # any measurements that needed to be removed before the swap
    last_layout = layout

    # If first_layer is still set, the circuit only has single-qubit gates
    # so we can use the initial layout to output the entire circuit
    if first_layer:
        layout = initial_layout
        for i, layer in enumerate(layerlist):
            dagcircuit_output.compose_back(layer["graph"], layout)

    # Parse openqasm_output into DAGCircuit object
    dag_unrrolled = DagUnroller(dagcircuit_output,
                                DAGBackend(basis.split(",")))
    dagcircuit_output = dag_unrrolled.expand_gates()
    return dagcircuit_output, initial_layout, last_layout
Map a DAGCircuit onto a CouplingGraph using swap gates.

    Args:
        circuit_graph (DAGCircuit): input DAG circuit
        coupling_graph (CouplingGraph): coupling graph to map onto
        initial_layout (dict): dict from qubits of circuit_graph to qubits
            of coupling_graph (optional)
        basis (str): basis string specifying basis of output DAGCircuit
        trials (int): number of trials.
        seed (int): initial seed.

    Returns:
        DAGCircuit: object containing a circuit equivalent to
        circuit_graph that respects couplings in coupling_graph, and
        a layout dict mapping qubits of circuit_graph into qubits
        of coupling_graph. The layout may differ from the initial_layout
        if the first layer of gates cannot be executed on the
        initial_layout. Finally, returned is the final layer qubit
        permutation that is needed to add measurements back in.

    Raises:
        MapperError: if there was any error during the mapping or with the
            parameters.
    
Map a DAGCircuit onto a CouplingGraph using swap gates.
Map a DAGCircuit onto a CouplingGraph using swap gates .
def swap_mapper(circuit_graph, coupling_graph,
                initial_layout=None,
                basis="cx,u1,u2,u3,id", trials=20, seed=None):
    if circuit_graph.width() > coupling_graph.size():
        raise MapperError("Not enough qubits in CouplingGraph")
    layerlist = list(circuit_graph.layers())
    logger.debug("schedule:")
    for i, v in enumerate(layerlist):
        logger.debug("    %d: %s", i, v["partition"])
    if initial_layout is not None:
        circ_qubits = circuit_graph.get_qubits()
        coup_qubits = coupling_graph.get_qubits()
        qubit_subset = []
        for k, v in initial_layout.items():
            qubit_subset.append(v)
            if k not in circ_qubits:
                raise MapperError("initial_layout qubit %s[%d] not in input "
                                  "DAGCircuit" % (k[0], k[1]))
            if v not in coup_qubits:
                raise MapperError("initial_layout qubit %s[%d] not in input "
                                  "CouplingGraph" % (v[0], v[1]))
    else:
        qubit_subset = coupling_graph.get_qubits()
        qubit_subset = qubit_subset[0:circuit_graph.width()]
        initial_layout = {a: b for a, b in
                          zip(circuit_graph.get_qubits(), qubit_subset)}
    layout = initial_layout.copy()
    layout_max_index = max(map(lambda x: x[1]+1, layout.values()))
    dagcircuit_output = DAGCircuit()
    dagcircuit_output.name = circuit_graph.name
    dagcircuit_output.add_qreg("q", layout_max_index)
    for name, size in circuit_graph.cregs.items():
        dagcircuit_output.add_creg(name, size)
    identity_wire_map = {}
    for j in range(layout_max_index):
        identity_wire_map[("q", j)] = ("q", j)
    for name, size in circuit_graph.cregs.items():
        for j in range(size):
            identity_wire_map[(name, j)] = (name, j)
    first_layer = True  
    logger.debug("initial_layout = %s", layout)
    for i, layer in enumerate(layerlist):
        success_flag, best_circ, best_d, best_layout, trivial_flag \
            = layer_permutation(layer["partition"], layout,
                                qubit_subset, coupling_graph, trials, seed)
        logger.debug("swap_mapper: layer %d", i)
        logger.debug("swap_mapper: success_flag=%s,best_d=%s,trivial_flag=%s",
                     success_flag, str(best_d), trivial_flag)
        if not success_flag:
            logger.debug("swap_mapper: failed, layer %d, "
                         "retrying sequentially", i)
            serial_layerlist = list(layer["graph"].serial_layers())
            for j, serial_layer in enumerate(serial_layerlist):
                success_flag, best_circ, best_d, best_layout, trivial_flag \
                    = layer_permutation(serial_layer["partition"],
                                        layout, qubit_subset, coupling_graph,
                                        trials, seed)
                logger.debug("swap_mapper: layer %d, sublayer %d", i, j)
                logger.debug("swap_mapper: success_flag=%s,best_d=%s,"
                             "trivial_flag=%s",
                             success_flag, str(best_d), trivial_flag)
                if not success_flag:
                    raise MapperError("swap_mapper failed: " +
                                      "layer %d, sublayer %d" % (i, j) +
                                      ", \"%s\"" %
                                      serial_layer["graph"].qasm(
                                          no_decls=True,
                                          aliases=layout))
                if trivial_flag and first_layer:
                    logger.debug("swap_mapper: skip to next sublayer")
                    continue
                layout = best_layout
                dagcircuit_output.compose_back(
                    swap_mapper_layer_update(j,
                                             first_layer,
                                             best_layout,
                                             best_d,
                                             best_circ,
                                             serial_layerlist),
                    identity_wire_map)
                if first_layer:
                    initial_layout = layout
                    first_layer = False
        else:
            layout = best_layout
            dagcircuit_output.compose_back(
                swap_mapper_layer_update(i,
                                         first_layer,
                                         best_layout,
                                         best_d,
                                         best_circ,
                                         layerlist),
                identity_wire_map)
            if first_layer:
                initial_layout = layout
                first_layer = False
    last_layout = layout
    if first_layer:
        layout = initial_layout
        for i, layer in enumerate(layerlist):
            dagcircuit_output.compose_back(layer["graph"], layout)
    dag_unrrolled = DagUnroller(dagcircuit_output,
                                DAGBackend(basis.split(",")))
    dagcircuit_output = dag_unrrolled.expand_gates()
    return dagcircuit_output, initial_layout, last_layout
def swap_mapper ( circuit_graph , coupling_graph , initial_layout = None , basis = "cx,u1,u2,u3,id" , trials = 20 , seed = None ) : if circuit_graph . width ( ) > coupling_graph . size ( ) : raise MapperError ( "Not enough qubits in CouplingGraph" ) layerlist = list ( circuit_graph . layers ( ) ) logger . debug ( "schedule:" ) for i , v in enumerate ( layerlist ) : logger . debug ( "    %d: %s" , i , v [ "partition" ] ) if initial_layout is not None : circ_qubits = circuit_graph . get_qubits ( ) coup_qubits = coupling_graph . get_qubits ( ) qubit_subset = [ ] for k , v in initial_layout . items ( ) : qubit_subset . append ( v ) if k not in circ_qubits : raise MapperError ( "initial_layout qubit %s[%d] not in input " "DAGCircuit" % ( k [ 0 ] , k [ 1 ] ) ) if v not in coup_qubits : raise MapperError ( "initial_layout qubit %s[%d] not in input " "CouplingGraph" % ( v [ 0 ] , v [ 1 ] ) ) else : qubit_subset = coupling_graph . get_qubits ( ) qubit_subset = qubit_subset [ 0 : circuit_graph . width ( ) ] initial_layout = { a : b for a , b in zip ( circuit_graph . get_qubits ( ) , qubit_subset ) } layout = initial_layout . copy ( ) layout_max_index = max ( map ( lambda x : x [ 1 ] + 1 , layout . values ( ) ) ) dagcircuit_output = DAGCircuit ( ) dagcircuit_output . name = circuit_graph . name dagcircuit_output . add_qreg ( "q" , layout_max_index ) for name , size in circuit_graph . cregs . items ( ) : dagcircuit_output . add_creg ( name , size ) identity_wire_map = { } for j in range ( layout_max_index ) : identity_wire_map [ ( "q" , j ) ] = ( "q" , j ) for name , size in circuit_graph . cregs . items ( ) : for j in range ( size ) : identity_wire_map [ ( name , j ) ] = ( name , j ) first_layer = True logger . debug ( "initial_layout = %s" , layout ) for i , layer in enumerate ( layerlist ) : success_flag , best_circ , best_d , best_layout , trivial_flag = layer_permutation ( layer [ "partition" ] , layout , qubit_subset , coupling_graph , trials , seed ) logger . debug ( "swap_mapper: layer %d" , i ) logger . debug ( "swap_mapper: success_flag=%s,best_d=%s,trivial_flag=%s" , success_flag , str ( best_d ) , trivial_flag ) if not success_flag : logger . debug ( "swap_mapper: failed, layer %d, " "retrying sequentially" , i ) serial_layerlist = list ( layer [ "graph" ] . serial_layers ( ) ) for j , serial_layer in enumerate ( serial_layerlist ) : success_flag , best_circ , best_d , best_layout , trivial_flag = layer_permutation ( serial_layer [ "partition" ] , layout , qubit_subset , coupling_graph , trials , seed ) logger . debug ( "swap_mapper: layer %d, sublayer %d" , i , j ) logger . debug ( "swap_mapper: success_flag=%s,best_d=%s," "trivial_flag=%s" , success_flag , str ( best_d ) , trivial_flag ) if not success_flag : raise MapperError ( "swap_mapper failed: " + "layer %d, sublayer %d" % ( i , j ) + ", \"%s\"" % serial_layer [ "graph" ] . qasm ( no_decls = True , aliases = layout ) ) if trivial_flag and first_layer : logger . debug ( "swap_mapper: skip to next sublayer" ) continue layout = best_layout dagcircuit_output . compose_back ( swap_mapper_layer_update ( j , first_layer , best_layout , best_d , best_circ , serial_layerlist ) , identity_wire_map ) if first_layer : initial_layout = layout first_layer = False else : layout = best_layout dagcircuit_output . compose_back ( swap_mapper_layer_update ( i , first_layer , best_layout , best_d , best_circ , layerlist ) , identity_wire_map ) if first_layer : initial_layout = layout first_layer = False last_layout = layout if first_layer : layout = initial_layout for i , layer in enumerate ( layerlist ) : dagcircuit_output . compose_back ( layer [ "graph" ] , layout ) dag_unrrolled = DagUnroller ( dagcircuit_output , DAGBackend ( basis . split ( "," ) ) ) dagcircuit_output = dag_unrrolled . expand_gates ( ) return dagcircuit_output , initial_layout , last_layout
Map a DAGCircuit onto a CouplingGraph using swap gates.
Map a DAGCircuit onto a CouplingGraph using swap gates .
"""Map a DAGCircuit onto a CouplingGraph using swap gates.

    Args:
        circuit_graph (DAGCircuit): input DAG circuit
        coupling_graph (CouplingGraph): coupling graph to map onto
        initial_layout (dict): dict from qubits of circuit_graph to qubits
            of coupling_graph (optional)
        basis (str): basis string specifying basis of output DAGCircuit
        trials (int): number of trials.
        seed (int): initial seed.

    Returns:
        DAGCircuit: object containing a circuit equivalent to
        circuit_graph that respects couplings in coupling_graph, and
        a layout dict mapping qubits of circuit_graph into qubits
        of coupling_graph. The layout may differ from the initial_layout
        if the first layer of gates cannot be executed on the
        initial_layout. Finally, returned is the final layer qubit
        permutation that is needed to add measurements back in.

    Raises:
        MapperError: if there was any error during the mapping or with the
            parameters.
    """ # Schedule the input circuit # Check the input layout # Supply a default layout # Find swap circuit to preceed to each layer of input circuit # Construct an empty DAGCircuit with one qreg "q" # and the same set of cregs as the input circuit # Make a trivial wire mapping between the subcircuits # returned by swap_mapper_layer_update and the circuit # we are building # True until first layer is output # Iterate over layers # Attempt to find a permutation for this layer # If this fails, try one gate at a time in this layer # Go through each gate in the layer # Give up if we fail again # If this layer is only single-qubit gates, # and we have yet to see multi-qubit gates, # continue to the next inner iteration # Update the record of qubit positions for each inner iteration # Update the QASM # Update initial layout # Update the record of qubit positions for each iteration # Update the QASM # Update initial layout # This is the final layout that we need to correctly replace # any measurements that needed to be removed before the swap # If first_layer is still set, the circuit only has single-qubit gates # so we can use the initial layout to output the entire circuit # Parse openqasm_output into DAGCircuit object
object containing a circuit equivalent to
circuit_graph that respects couplings in coupling_graph, and
a layout dict mapping qubits of circuit_graph into qubits
of coupling_graph. The layout may differ from the initial_layout
if the first layer of gates cannot be executed on the
initial_layout. Finally, returned is the final layer qubit
permutation that is needed to add measurements back in.
object containing a circuit equivalent to circuit_graph that respects couplings in coupling_graph and a layout dict mapping qubits of circuit_graph into qubits of coupling_graph . The layout may differ from the initial_layout if the first layer of gates cannot be executed on the initial_layout . Finally returned is the final layer qubit permutation that is needed to add measurements back in .
DAGCircuit
if there was any error during the mapping or with the
parameters.
if there was any error during the mapping or with the parameters .
MapperError
circuit_graph
input DAG circuit
input DAG circuit
coupling_graph
coupling graph to map onto
coupling graph to map onto
initial_layout
dict from qubits of circuit_graph to qubits
of coupling_graph (optional)
dict from qubits of circuit_graph to qubits of coupling_graph ( optional )
basis
basis string specifying basis of output DAGCircuit
basis string specifying basis of output DAGCircuit
trials
number of trials.
number of trials .
seed
None