Ejemplo n.º 1
0
def try_embedding(n_reads, solver, print_embedding=True):
	start_total = time.time()

	# Create test
	start_test = time.time()
	_, reads = create_test(num_reads=n_reads)
	test_creation_time = time.time() - start_test

	# Prepare the data
	tspAdjM = reads_to_tspAdjM(reads)
	quboAdjM = tspAdjM_to_quboAdjM(tspAdjM, -1.6, 1.6, 1.6)
	Q = quboAdjM_to_quboDict(quboAdjM)

	# Try to embed Q into a valid graph for the pegasus topology
	start_embedding = time.time()
	edgelist = solver.edges
	adjdict = edgelist_to_adjacency(edgelist)
	embed = minorminer.find_embedding(Q, edgelist)
	Q_embeded = embed_qubo(Q, embed, adjdict)
	embedding_time = time.time() - start_embedding

	total_time = time.time() - start_total

	print('Successful: {} reads, {} nodes graph, {:.6f}s test creation time, {:.6f}s embedding time, {:.6f}s total time'.format(
		len(reads), len(reads)*len(reads), test_creation_time, embedding_time, total_time))
Ejemplo n.º 2
0
Archivo: 3.py Proyecto: Ocete/TFG
def solve_qubo_dwave(Q, num_reads=1000):
    # Create the solver (connecting to D-Wave) and the Sampler
    config_file = '../dwave.conf'
    client = Client.from_config(config_file, profile='ocete')
    solver = client.get_solver(
    )  # Available QPUs: DW_2000Q_2_1 (2038 qubits), DW_2000Q_5 (2030 qubits)
    dwsampler = DWaveSampler(config_file=config_file)

    # We need to embed Q into a valid graph for the D-Wave architecture
    edgelist = solver.edges
    adjdict = edgelist_to_adjacency(edgelist)
    embed = minorminer.find_embedding(Q, edgelist)
    Q_embeded = embed_qubo(Q, embed, adjdict)

    # Obtain the response from the solver. This is the actual D-Wave execution!
    start = time.time()
    response_qpt = dwsampler.sample_qubo(Q_embeded, num_reads=num_reads)
    qpu_time = time.time() - start
    client.close()

    # Transform the response from the embeded graph to our original architecture
    bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
    unembedded = unembed_sampleset(response_qpt,
                                   embed,
                                   bqm,
                                   chain_break_method=majority_vote)

    # Order the solutions by lower energy
    return unembedded, qpu_time
Ejemplo n.º 3
0
def solve_qubo_dwave(Q,
                     n_genome_reads,
                     num_reads=100,
                     label='',
                     annealing_time=20):
    # Create the solver (connecting to D-Wave) and the Sampler
    config_file = '../dwave_adv.conf'
    client = Client.from_config(config_file, profile='ocete')
    solver = client.get_solver('Advantage_system1.1')
    dwsampler = DWaveSampler(
        solver={
            'qpu': True,
            'topology__type': 'pegasus',
            'annealing_time': annealing_time
        },  # Watch out, Leap doesn seem to take into account
        # this parameter, you have to give it as  a paramater in the dwsampler.sample() call
        token=token,
        endpoint=endpoint)

    # We need to embed Q into a valid graph for the D-Wave architecture
    adjdict = edgelist_to_adjacency(solver.edges)
    embed = minorminer.find_embedding(Q, solver.edges)
    Q_embeded = embed_qubo(Q, embed, adjdict)

    # Obtain the response from the solver. This is the actual D-Wave execution!
    start = time.time()
    response_qpt = dwsampler.sample_qubo(Q_embeded,
                                         num_reads=num_reads,
                                         label=label,
                                         annealing_time=annealing_time)
    qpu_time = time.time() - start
    client.close()

    # Transform the response from the embeded graph to our original architecture
    bqm = dimod.BinaryQuadraticModel.from_qubo(Q)
    unembedded = unembed_sampleset(response_qpt,
                                   embed,
                                   bqm,
                                   chain_break_method=majority_vote)

    # Sort the solutions from lowest energy and format them to quboDict format
    unformated_solutions_list = sorted(unembedded.record, key=lambda x: +x[1])
    solutions_list = []
    for sol, energy, num_appereances in unformated_solutions_list:
        solutions_list.append([
            rebuild_quboDict_from_vector(sol, n_genome_reads), energy,
            num_appereances
        ])

    return solutions_list, qpu_time, get_max_chain_length(embed)
Ejemplo n.º 4
0
                x = x % 8
                side = int(x / 4)
                x = x % 4
                var = x + 4 * row if side else x + 4 * col
                unembedded['q{}'.format(var)] = 1
        if list(unembedded.values()).count(1) == 1:
            hits += num_occurrences
            correct = True
        # print(str(unembedded) + " " + str(num_occurrences) + " " + str(correct))
    return hits / shots


problem_size = 8
shots = 1000

Q = create_xor_qubo(problem_size)
print("QUBO:")
print(Q)
embedding = create_embedding(problem_size)
print("Embedding:")
print(embedding)

tQ = embed_qubo(Q, embedding, chimera_graph(16), chain_strength=0.9)
print("Embedded QUBO:")
print(tQ)

# if tQ:
#     response = DWaveSampler().sample_qubo(tQ, num_reads=shots)
#     print("Response:")
#     print(get_score(response, problem_size, shots))
# Express objective function and compile it to model
H_obj = H_cost + Placeholder('lam') * (H_city + H_time)
model = H_obj.compile()

# --- Solve QUBO and unembed samplesn ---

# Get the QUBO matrix from the model
feed_dict = {'lam': 5.0}  # the coefficient of constraints
qubo, offset = model.to_qubo(feed_dict=feed_dict)

adjacency = {key: 1.0 for key in qubo.keys() if key[0] != key[1]}

# Run QUBO on DW_2000Q_5
sampler = DWaveSampler(solver='DW_2000Q_5')
embedding = find_embedding(adjacency, sampler.edgelist)
qubo_emb = embed_qubo(qubo, embedding, sampler.adjacency)
response = sampler.sample_qubo(qubo_emb,
                               num_reads=1000,
                               postprocess='optimization')

# Unembed samples by specifying chain_break_method argument of unembed_sampleset
bqm = dimod.BinaryQuadraticModel.from_qubo(qubo)
# majority_vote (default)
sample_majority_vote = unembed_sampleset(response,
                                         embedding,
                                         bqm,
                                         chain_break_method=majority_vote)
# discard
sample_discard = unembed_sampleset(response,
                                   embedding,
                                   bqm,
Ejemplo n.º 6
0
                    idx2 = index(nurse, day2)
                    Q[idx, idx2] += 2 * lagrange_soft_nurse * preference(
                        nurse, day) * preference(nurse, day2)

        ## Solve
        ## 解きます

        ### Graph embedding
        topology = 'pegasus'  # 'chimera' or 'pegasus'
        sampler = DWaveSampler(solver={
            'topology__type': topology,
            'qpu': True
        })

        embedding = find_embedding(Q.keys(), sampler.edgelist)
        embeddedQ = embed_qubo(Q, embedding, sampler.adjacency)

        ### Energy offset
        ### エネルギー オフセット
        e_offset = lagrange_hard_shift * days * workforce(1)**2
        e_offset += lagrange_soft_nurse * nurses * duty_days**2

        ### BQM
        bqm = BinaryQuadraticModel.from_qubo(embeddedQ, offset=e_offset)
        sbqm = BinaryQuadraticModel.from_qubo(Q, offset=e_offset)

        # Sample solution
        # 解をサンプリングします
        print("Connected to {}. N = {}, D = {}".format(sampler.solver.id,
                                                       nurses, days))
        results = sampler.sample(bqm, num_reads=numSampling)