How to use the minorminer.find_embedding function in minorminer

To help you get started, we’ve selected a few minorminer examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lanl / qmasm / src / qmasm / solve.py View on Github external
# Given verbose=0, invoke minorminer directly.
        if "verbose" not in kwargs or kwargs["verbose"] == 0:
            # Convert all keys to integers for consistency.
            embedding = minorminer.find_embedding(edges, mm_adj, **kwargs)
            return {int(k): v for k, v in embedding.items()}

        # minorminer's find_embedding is hard-wired to write to stdout.
        # Trick it into writing into a pipe instead.
        sepLine = "=== EMBEDDING ===\n"
        r, w = os.pipe()
        pid = os.fork()
        if pid == 0:
            # Child -- perform the embedding.
            os.close(r)
            os.dup2(w, sys.stdout.fileno())
            embedding = minorminer.find_embedding(edges, mm_adj, **kwargs)
            sys.stdout.flush()
            os.write(w, sepLine.encode())
            os.write(w, (json.dumps(embedding) + "\n").encode())
            os.close(w)
            os._exit(0)
        else:
            # Parent -- report the embedding's progress.
            os.close(w)
            pipe = os.fdopen(r, "r", 10000)
            while True:
                try:
                    rstr = pipe.readline()
                    if rstr == sepLine:
                        break
                    if rstr == "":
                        self.qmasm.abend("Embedder failed to terminate properly")
github dwave-examples / factoring / factoring / interfaces.py View on Github external
####################################################################################################

    sample_time = time.time()

    # get QPU sampler
    sampler = DWaveSampler(solver=dict(qpu=True))
    _, target_edgelist, target_adjacency = sampler.structure

    embedding = None
    if use_saved_embedding:
        # load a pre-calculated embedding
        from factoring.embedding import embeddings
        embedding = embeddings.get(sampler.solver.id)
    if not embedding:
        # get the embedding
        embedding = minorminer.find_embedding(bqm.quadratic, target_edgelist)
        if bqm and not embedding:
            raise ValueError("no embedding found")

    # apply the embedding to the given problem to map it to the sampler
    bqm_embedded = dimod.embed_bqm(bqm, embedding, target_adjacency, 3.0)

    # draw samples from the QPU
    kwargs = {}
    if 'num_reads' in sampler.parameters:
        kwargs['num_reads'] = 50
    if 'answer_mode' in sampler.parameters:
        kwargs['answer_mode'] = 'histogram'
    response = sampler.sample(bqm_embedded, **kwargs)

    # convert back to the original problem space
    response = dimod.unembed_response(response, embedding, source_bqm=bqm)
github eclipse / xacc / quantum_v1 / plugins / cmr / tpls / minorminer / examples / fourcolor.py View on Github external
#   1. fix the embedding `(z,u) -> (z,u)` for all dummy nodes
    #   2. for each target block `i` with orientation `u`, and for each source
    #     node `z`, add the target edge `((z,u), i)`
    #   3. for each source node `z` and each orientation `u`, add the source
    #     edge `((z,u), z)`

    fix_chains = {}
    for z in source_n:
        for u in (0, 1):
            source_e.append(((z, u), z))
            fix_chains[z, u] = [(z, u)]
        for u, i in ublocks.values():
            fabric_e.append(((z, u), i))

    # first, grab a few embeddings in the quotient graph. this is super fast
    embs = filter(None, [find_embedding(source_e, fabric_e,
                                        fixed_chains=fix_chains,
                                        chainlength_patience=0,
                                        **args) for _ in range(10)])

    # select the best-looking candidate so far
    emb = min(embs, key=lambda e: sorted((len(c)
                                          for c in e.values()), reverse=True))

    # work down the chainlengths in our embeding
    for _ in range(10):
        emb = find_embedding(source_e, fabric_e,
                             fixed_chains=fix_chains,
                             initial_chains=emb,
                             chainlength_patience=3,
                             skip_initialization=True,
                             **args)
github eclipse / xacc / quantum_v1 / plugins / cmr / tpls / minorminer / examples / fourcolor.py View on Github external
if __name__ == "__main__":
    # first, we construct a Chimera graph
    G = dnx.chimera_graph(16)
    labs = nx.get_node_attributes(G, 'chimera_index')
    unlab = {d: i for i, d in labs.items()}
    H = nx.relabel_nodes(G, labs)

    # Now we take a graph to be colored
    graph = nx.generators.triangular_lattice_graph(8, 8)

    # for a basis of comparison, let's try to embed this without the quotient
    graph4 = graph_coloring_qubo(graph, 4)
    c = clock()
    emb = find_embedding(graph4.edges(), H.edges(),
                         verbose=0, chainlength_patience=30)
    try:
        print("raw embedding %d seconds, " % (clock() - c), end='')
        cl = max(len(c) for c in emb.values())
        print("maximum chainlength %d" % cl)
    except:
        print("failure")

    # we embed it using the block quotient,
    c = clock()
    emb = embed_with_quotient(graph, H, 16, 16, 4)
    # and then translate back to integer indices
    print("quotient embedding %d seconds, maximum chainlength %d" % (clock() - c, max(len(c) for c in emb.values())))

    # finally, we translate the embedding back to integer labels
    newemb = {v: [unlab[q] for q in c] for v, c in emb.items()}
github lanl / qmasm / src / qmasm / solve.py View on Github external
def _find_embedding(self, edges, adj, max_qubits, **kwargs):
        "Wrap minorminer.find_embedding with a version that intercepts its output."
        # Minorminer accepts the hardware adjacency as a list of
        # pairs, not a map from each node to its neighbors.
        mm_adj = [(u, v) for u in adj for v in adj[u]]

        # Given verbose=0, invoke minorminer directly.
        if "verbose" not in kwargs or kwargs["verbose"] == 0:
            # Convert all keys to integers for consistency.
            embedding = minorminer.find_embedding(edges, mm_adj, **kwargs)
            return {int(k): v for k, v in embedding.items()}

        # minorminer's find_embedding is hard-wired to write to stdout.
        # Trick it into writing into a pipe instead.
        sepLine = "=== EMBEDDING ===\n"
        r, w = os.pipe()
        pid = os.fork()
        if pid == 0:
            # Child -- perform the embedding.
            os.close(r)
            os.dup2(w, sys.stdout.fileno())
            embedding = minorminer.find_embedding(edges, mm_adj, **kwargs)
            sys.stdout.flush()
            os.write(w, sepLine.encode())
            os.write(w, (json.dumps(embedding) + "\n").encode())
            os.close(w)

minorminer

heuristic algorithm to find graph minor embeddings

Apache-2.0
Latest version published 24 days ago

Package Health Score

72 / 100
Full package analysis

Popular minorminer functions

Similar packages