Exemplo n.º 1
0
def sample_BQM(BQM):
    '''
    :param BQM: BQM model
    :return: simplified model
    '''
    sampler = ExactSolver()
    return sampler.sample(BQM)
Exemplo n.º 2
0
def scheduling(time, location, length, mandatory):
    if time:                                 # Business hours
        return (location and mandatory)      # In office and mandatory participation
    else:                                    # Outside business hours
        return ((not location) and length)   # Teleconference for a short duration

    import dwavebinarycsp
    csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
    csp.add_constraint(scheduling, ['time', 'location', 'length', 'mandatory'])

    bqm = dwavebinarycsp.stitch(csp)
    bqm.linear
    {'length': -2.0, 'location': 2.0, 'mandatory': 0.0, 'time': 2.0}
    bqm.quadratic
    {('location', 'length'): 2.0,
     ('mandatory', 'length'): 0.0,
     ('mandatory', 'location'): -2.0,
     ('time', 'length'): 0.0,
     ('time', 'location'): -4.0,
     ('time', 'mandatory'): 0.0}

    from dimod.reference.samplers import ExactSolver
    sampler = ExactSolver()
    solution = sampler.sample(bqm)

    min_energy = next(solution.data(['energy']))[0]
    print(min_energy)
    -2.0

    for sample, energy in solution.data(['sample', 'energy']):
        if energy == min_energy:
            time = 'business hours' if sample['time'] else 'evenings'
            location = 'office' if sample['location'] else 'home'
            length = 'short' if sample['length'] else 'long'
            mandatory = 'mandatory' if sample['mandatory'] else 'optional'
            print("During {} at {}, you can schedule a {} meeting that is {}".format(time, location, length, mandatory))



     if energy == min_energy:
         time = 'business hours' if sample['time'] else 'evenings'
         location = 'office' if sample['location'] else 'home'
         length = 'short' if sample['length'] else 'long'
         mandatory = 'mandatory' if sample['mandatory'] else 'optional'
         print("During {} at {}, you can schedule a {} meeting that is {}".format(time, location, length, mandatory))
Exemplo n.º 3
0
def get_solver(solver_type):
    solver = None
    if solver_type == 'standard':
        solver = EmbeddingComposite(DWaveSampler())
    if solver_type == 'hybrid':
        solver = hybrid_solver()
    if solver_type == 'kerberos':
        solver = KerberosSampler()
    if solver_type == 'qbsolv':
        solver = QBSolv()
    if solver_type == 'exact':
        solver = ExactSolver()
    return solver
Exemplo n.º 4
0
def get_sampler(sampler_name, graph):
    from config import REGIST_INFO_PATH

    with open(REGIST_INFO_PATH, 'r') as f:
        regist_info = json.load(f)

    if sampler_name == 'exact':
        if check_graph(graph):
            sampler = ExactSolver()
        else:
            return TOO_MANY_NODES

    elif sampler_name == 'simulated annealing':
        return SimulatedAnnealingSampler()

    elif sampler_name == 'dwave':
        if DWAVE_ALLOWED:
            sampler = EmbeddingComposite(DWaveSampler(**regist_info))
        else:
            return DWAVE_NOT_ALLOWED

    return sampler
Exemplo n.º 5
0
    variables = [province + str(i) for i in range(colors)]
    csp.add_constraint(one_color_configurations, variables)

# Add constraint that each pair of nodes with a shared edge not both select one color
for neighbor in neighbors:
    v, u = neighbor
    for i in range(colors):
        variables = [v + str(i), u + str(i)]
        csp.add_constraint(not_both_1, variables)

# %%
bqm = dwavebinarycsp.stitch(csp)
print('bqm', bqm.linear)

# %%
sampler = ExactSolver()
# below would cause memory overflow. (over 20GB of mem.)
response = sampler.sample(bqm)
print(response)


# %%
# Function that plots a returned sample
def plot_map(sample):
    G = nx.Graph()
    G.add_nodes_from(provinces)
    G.add_edges_from(neighbors)
    # Translate from binary to integer color representation
    color_map = {}
    for province in provinces:
        for i in range(colors):
Exemplo n.º 6
0
import numpy as np
import matplotlib.pyplot as plt

a5 = nx.star_graph(4)
plt.subplot(121)

nx.draw(a5, with_labels=True, front_weight='bold')

# In[4]:

#Solve the graph minimum vertex cover on the CPU

from dimod.reference.samplers import ExactSolver
import dwave_networkx as dnx

sampler = ExactSolver()
print(dnx.min_vertex_cover(a5, sampler))

# In[6]:

#step 3 solve the graphs minimum vertex cover on the QPU

from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite

sampler = EmbeddingComposite(DWaveSampler())
print(dnx.min_vertex_cover(a5, sampler))

# In[7]:

#Step 4 try with bigger graph
Exemplo n.º 7
0
# Empezaremos con un caso muy simple

J = {(1,1):1,(1,2):-2,(1,3): 6,(1,4):3,(2,1):-2,(2,2):4,(2,3):-12,(2,4):-6,(3,1): 6,(3,2):-12,(3,3):36,(3,4):18,(4,1):3,(4,2):-6,(4,3):18,(4,4):9}

h = {}
model = dimod.BinaryQuadraticModel(h, J, 0.0, dimod.SPIN)

print("El modelo que vamos a resolver es")
print(model)
print()

# Podemos resolver el modelo de forma exacta


from dimod.reference.samplers import ExactSolver
sampler = ExactSolver()
solution = sampler.sample(model)
print("La solucion exacta es")
print(solution)
print()


# O con *simulated annealing* (un método heurístico de optimización para ordenadores clásicos)


sampler = dimod.SimulatedAnnealingSampler()
response = sampler.sample(model, num_reads=10)
print("La solucion con simulated annealing es")
print(response)
print()
Exemplo n.º 8
0
lower values for valid states of the NOT gate (e.g., x1=0,x2=1) and higher for invalid states (e.g., x1=0,x2=0).
'''

import dwavebinarycsp
import dwavebinarycsp.factories.constraint.gates as gates
csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
csp.add_constraint(gates.and_gate(['x1', 'x2', 'y1']))  # add an AND gate
bqm = dwavebinarycsp.stitch(csp)

''' The members of the two dicts are linear and quadratic coefficients, respectively, the third term is a constant offset associated with the model, and the fourth shows the variable types in this model are binary. '''
print(bqm) # BQM of the AND gate created

print('################################################################################')

from dimod.reference.samplers import ExactSolver
sampler = ExactSolver()
response = sampler.sample(bqm)

print(response)

for datum in response.data():
	print(datum)

for sample, energy in response.data(fields=['sample', 'energy'], sorted_by='energy'):
	print(sample, energy)

print('################################################################################')

from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
sampler = EmbeddingComposite(DWaveSampler()) # EmbeddingComposite() composite that maps unstructured problems to the graph structure of the selected sampler, a process known as minor-embedding.
# Create a constraint from this function and adds it to CSP instance, csp,
# instantiated with binary variables.
import dwavebinarycsp
csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
csp.add_constraint(scheduling, ['time', 'location', 'length', 'mandatory'])

# Display the BQM’s linear and quadratic coefficients, qi and qi,j respectively in
# ∑Niqixi+∑Ni<jqi,jxixj, which are the inputs for programming the quantum computer.
bqm = dwavebinarycsp.stitch(csp)
bqm.linear
bqm.quadratic

# Solving classically on a CPU
from dimod.reference.samplers import ExactSolver
sampler = ExactSolver()
solution = sampler.sample(bqm)

# Sets variable min_energy to the BQM’s lowest value, which is in the first record of
# the returned result
min_energy = next(solution.data(['energy']))[0]
print(min_energy)

# Print all solutions (assignments of variables) for which the BQM has its minimum value.
for sample, energy in solution.data(['sample', 'energy']):
    if energy == min_energy:
        time = 'business hours' if sample['time'] else 'evenings'
        location = 'office' if sample['location'] else 'home'
        length = 'short' if sample['length'] else 'long'
        mandatory = 'mandatory' if sample['mandatory'] else 'optional'
        print(
Exemplo n.º 10
0
csp.add_constraint(scheduling, ['time', 'location', 'length', 'mandatory'])

bqm = dwavebinarycsp.stitch(csp)
bqm.linear
{'length': -2.0, 'location': 2.0, 'mandatory': 0.0, 'time': 2.0}
bqm.quadratic
{
    ('location', 'length'): 2.0,
    ('mandatory', 'length'): 0.0,
    ('mandatory', 'location'): -2.0,
    ('time', 'length'): 0.0,
    ('time', 'location'): -4.0,
    ('time', 'mandatory'): 0.0
}

### Classical CPU
from dimod.reference.samplers import ExactSolver
sampler = ExactSolver()
solution = sampler.sample(bqm)
min_energy = next(solution.data(['energy']))[0]
print(min_energy)

for sample, energy in solution.data(['sample', 'energy']):
    if energy == min_energy:
        time = 'business hours' if sample['time'] else 'evenings'
        location = 'office' if sample['location'] else 'home'
        length = 'short' if sample['length'] else 'long'
        mandatory = 'mandatory' if sample['mandatory'] else 'optional'
        print(
            "During {} at {}, you can schedule a {} meeting that is {}".format(
                time, location, length, mandatory))
def factor(P, use_saved_embedding=False):

    ####################################################################################################
    # get circuit
    ####################################################################################################

    construction_start_time = time.time()

    validate_input(P, range(2**6))

    # get constraint satisfaction problem
    csp = dbc.factories.multiplication_circuit(3)

    # get binary quadratic model
    bqm = dbc.stitch(csp, min_classical_gap=.1)

    # we know that multiplication_circuit() has created these variables
    p_vars = ['p0', 'p1', 'p2', 'p3', 'p4', 'p5']

    # convert P from decimal to binary
    fixed_variables = dict(zip(reversed(p_vars), "{:06b}".format(P)))
    fixed_variables = {var: int(x) for (var, x) in fixed_variables.items()}

    # fix product qubits
    for var, value in fixed_variables.items():
        bqm.fix_variable(var, value)

    log.debug('bqm construction time: %s',
              time.time() - construction_start_time)

    ####################################################################################################
    # run problem
    ####################################################################################################

    sample_time = time.time()

    # get QPU sampler
    # sampler = DWaveSampler(solver_features=dict(online=True, name='DW_2000Q.*'))
    sampler = ExactSolver()
    #    _, target_edgelist, target_adjacency = sampler.structure
    '''
    if use_saved_embedding:
        # load a pre-calculated embedding
        from factoring.embedding import embeddings
        embedding = embeddings[sampler.solver.id]
    else:
        # 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, **kwargs)

    # convert back to the original problem space
    # response = dimod.unembed_response(response, embedding, source_bqm=bqm)

    #sampler.client.close()

    log.debug('embedding and sampling time: %s', time.time() - sample_time)

    ####################################################################################################
    # output results
    ####################################################################################################

    output = {
        "results": [],
        #    {
        #        "a": Number,
        #        "b": Number,
        #        "valid": Boolean,
        #        "numOfOccurrences": Number,
        #        "percentageOfOccurrences": Number
        #    }
        "timing": {
            "actual": {
                "qpuProcessTime": None  # microseconds
            }
        },
        "numberOfReads": None
    }

    # we know that multiplication_circuit() has created these variables
    a_vars = ['a0', 'a1', 'a2']
    b_vars = ['b0', 'b1', 'b2']

    # histogram answer_mode should return counts for unique solutions
    if 'num_occurrences' not in response.data_vectors:
        response.data_vectors['num_occurrences'] = [1] * len(response)

    # should equal num_reads
    total = sum(response.data_vectors['num_occurrences'])

    results_dict = OrderedDict()
    for sample, num_occurrences in response.data(['sample',
                                                  'num_occurrences']):
        # convert A and B from binary to decimal
        a = b = 0
        for lbl in reversed(a_vars):
            a = (a << 1) | sample[lbl]
        for lbl in reversed(b_vars):
            b = (b << 1) | sample[lbl]
        # aggregate results by unique A and B values (ignoring internal circuit variables)
        if (a, b, P) in results_dict:
            results_dict[(a, b, P)]["numOfOccurrences"] += num_occurrences
            results_dict[(a, b, P)]["percentageOfOccurrences"] = 100 * \
                results_dict[(a, b, P)]["numOfOccurrences"] / total
        else:
            results_dict[(a, b, P)] = {
                "a": a,
                "b": b,
                "valid": a * b == P,
                "numOfOccurrences": num_occurrences,
                "percentageOfOccurrences": 100 * num_occurrences / total
            }

    output['results'] = list(results_dict.values())
    output['numberOfReads'] = total
    if 'timing' in response.info:
        output['timing']['actual']['qpuProcessTime'] = response.info['timing'][
            'qpu_access_time']

    return output
Exemplo n.º 12
0
csp.add_constraint(
    scheduling,
    ['time', 'location', 'length', 'mandatory'
     ])  # create a constraint from this function and adds it to CSP instance

bqm = dwavebinarycsp.stitch(csp)  # convert the binary CSP to a BQM
print('bqm.linear', bqm.linear)
print('bqm.quadratic', bqm.quadratic)

print(
    '################################################################################'
)

# Solving Classically on a CPU
from dimod.reference.samplers import ExactSolver
sampler = ExactSolver()
solution = sampler.sample(
    bqm
)  # returns the BQM's value (energy) for every possible assignment of variable values.

min_energy = next(solution.data(['energy']))[0]
print(
    min_energy
)  # assignments of variables that do not violate any constraint-should have the lowest value of the BQM

for sample, energy in solution.data(['sample', 'energy']):
    if energy == min_energy:  # prints all those solutions (assignments of variables) for which the BQM has its minimum value.
        time = 'business hours' if sample['time'] else 'evenings'
        location = 'office' if sample['location'] else 'home'
        length = 'short' if sample['length'] else 'long'
        mandatory = 'mandatory' if sample['mandatory'] else 'optional'
Exemplo n.º 13
0
# Taken from documentation "Solving Problems on a D-Wave System"
# @ https://dwave-meta-doc.readthedocs.io/en/latest/overview/solving_problems.html

import dwavebinarycsp
import dwavebinarycsp.factories.constraint.gates as gates
from dimod.reference.samplers import ExactSolver
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)
csp.add_constraint(gates.and_gate(['x1', 'x2', 'y1']))  # add an AND gate
bqm = dwavebinarycsp.stitch(csp)

# ExactSovler() does not use QPU but runs locally
# it's good to test code locally
sampler = ExactSolver()
response = sampler.sample(bqm)    
for datum in response.data(['sample', 'energy']):
	print(datum.sample, datum.energy)

# Now execute same code on a D-Wave QPU
sampler = EmbeddingComposite(DWaveSampler())
response = sampler.sample(bqm, num_reads=1000)   
for datum in response.data(['sample', 'energy', 'num_occurrences']):
	print(datum.sample, datum.energy, "Occurrences: ", datum.num_occurrences)
Exemplo n.º 14
0
def Trace(g, v1, v2):
    # cs0 =dwavebinarycsp.Constraint.from_func(neigbor2,L(0)+L(1), dwavebinarycsp.BINARY,name='cs0')
    cs0 = dwavebinarycsp.Constraint.from_func(neigbor,
                                              L(0) + L(1) + ['res0'],
                                              dwavebinarycsp.BINARY,
                                              name='cs0')
    csp.add_constraint(cs0)

    #cs2 = dwavebinarycsp.Constraint.from_func(neigbor, L(1) + L(3) + ['res2'], dwavebinarycsp.BINARY, name='cs2')
    #cs2 = dwavebinarycsp.Constraint.from_func(neigbor2, L(1) + L(3), dwavebinarycsp.BINARY, name='cs2')
    #csp.add_constraint(cs2)

    cs1 = dwavebinarycsp.Constraint.from_func(neigbor,
                                              L(1) + L(2) + ['res3'],
                                              dwavebinarycsp.BINARY,
                                              name='cs1')
    csp.add_constraint(cs1)

    r1, c1 = v1
    r2, c2 = v2
    # Устанавливаем начальную и конечную вершины
    """
    setIntVar2(cs0, (0, 0), 2, 0)  # ряд вершины 1
    setIntVar2(cs0, (0, 1), 2, 0)  # колонка вершины 1
    setIntVar2(cs1, (2, 0), 2, 0)  # ряд вершины 2
    setIntVar2(cs1, (2, 1), 2, 2)  # колонка вершины 2
    """
    #bqm = dwavebinarycsp.stitch(csp,min_classical_gap=2.0, max_graph_size=9)

    setIntVar2(cs0, (0, 0), 2, r1)  # ряд вершины 1
    setIntVar2(cs0, (0, 1), 2, c1)  # колонка вершины 1
    setIntVar2(cs1, (2, 0), 2, r2)  # ряд вершины 2
    setIntVar2(cs1, (2, 1), 2, c2)  # колонка вершины 2

    bqm = dwavebinarycsp.stitch(csp, min_classical_gap=2.0, max_graph_size=8)
    #print(" Do stitch()")
    # print (bqm)

    # Проверка на локальной машине
    from dimod.reference.samplers import ExactSolver
    sampler = ExactSolver()
    solution = sampler.sample(bqm)
    """
    #Проверка на реальной машине
    from dwave.system.samplers import DWaveSampler
    from dwave.system.composites import EmbeddingComposite

    # Set up a D-Wave system as the sampler
    sampler = EmbeddingComposite(DWaveSampler())
    #sampler = EmbeddingComposite(DWaveSampler(endpoint='https://URL_to_my_D-Wave_system/', token='ABC-123456789012345678901234567890', solver='My_D-Wave_Solver'))
    solution = sampler.sample(bqm, num_reads=100)
    """

    print(solution)
    min_energy = next(solution.data(['energy']))[0]
    print(min_energy)

    res_sample = next(solution.data(['sample']))[0]
    print(res_sample)
    r1 = [res_sample[(1, 0, 0)],
          res_sample[(1, 0, 1)]]  # Собираем биты ряда узла 1
    res0 = res_sample['res0']
    if (not res0):
        return []
    # r1.append(res_sample[(1,0,0)])
    # r1.append(res_sample[(1,0,1)])
    nr = BinToInt(r1)  # номер ряда числом
    k = [res_sample[(1, 1, 0)],
         res_sample[(1, 1, 1)]]  # Собираем биты колонки узла 1
    nk = BinToInt(k)  # номер колонки числом

    return [v1, (nr, nk), v2]
Exemplo n.º 15
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# https://docs.ocean.dwavesys.com/en/latest/examples/min_vertex.html

import networkx as nx
s5 = nx.star_graph(4) # create a star graph where node 0 is hub to four other nodes.

# Solving Classically on a CPU

from dimod.reference.samplers import ExactSolver
sampler = ExactSolver() # returns the BQM's value for every possible assignment of variable values

import dwave_networkx as dnx
print(dnx.min_vertex_cover(s5, sampler)) # produce a BQM for our s5 graph and solve it on our selected sampler

print('################################################################################')

# Solving on a D-Wave System

from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite # EmbeddingComposite(), maps unstructured problems to the graph structure of the selected sampler, a process known as minor-embedding
sampler = EmbeddingComposite(DWaveSampler()) # endpoint='https://URL_to_my_D-Wave_system/', token='ABC-123456789012345678901234567890', solver='My_D-Wave_Solver'
print(dnx.min_vertex_cover(s5, sampler))

print('################################################################################')

w5 = nx.wheel_graph(5) # creates a new graph
print(dnx.min_vertex_cover(w5, sampler)) # solves on a D-Wave system
print(dnx.min_vertex_cover(w5, sampler))
Exemplo n.º 16
0
Ex = preprocessing.normalize([E])
for i in range(6):
    E[i] = Ex[0][i] / 10 * 3

A = [179.5, 408.5, 18.79, 119.26, 1777.02, 241.05]
Ax = preprocessing.normalize([A])
A = Ax[0]
B = 2

Number_of_data = 6
theta_1 = 0.33
theta_2 = 0.33
theta_3 = 0.33

gamma = theta_3 * B**2

for i in range(Number_of_data):
    hi_dict['Z{}'.format(i + 1)] = 0.5 * (theta_2 * Cov_Ri_Rj[i][i] +
                                          theta_3 * A[i]**2 - theta_1 * E[i] -
                                          2 * B * theta_3 * A[i])
    for j in range(i + 1, Number_of_data):
        J_i_j['Z{}'.format(i + 1),
              'Z{}'.format(j + 1)] = 0.25 * (theta_2 * Cov_Ri_Rj[i][j] +
                                             theta_3 * A[i] * A[j])

BQM = dimod.BinaryQuadraticModel(hi_dict, J_i_j, gamma, 'BINARY')
sampler = ExactSolver()
sampled = sampler.sample(BQM)

print(sampled)
Exemplo n.º 17
0
length = len(nodes)

A = 7
B = 1

diagonal = createDig(nodes, length, -2 * A)
matrix = fillMatrixC1(nodes, length, 2 * A)
matrix.update(fillMatrixC2(nodes, length, 2 * A))

# no edge
matrix.update(fillMatrixC3('b', 'd', length, 2 * A))

# weigth the edges that exists
matrix.update(fillMatrixC3('a', 'b', length, 3 * B))
matrix.update(fillMatrixC3('b', 'c', length, 4 * B))
matrix.update(fillMatrixC3('c', 'd', length, 5 * B))
matrix.update(fillMatrixC3('a', 'c', length, 6 * B))
matrix.update(fillMatrixC3('a', 'd', length, 7 * B))

printMatrix(diagonal, matrix, nodes, length)

# qubo matrix
qubo = dimod.BinaryQuadraticModel(diagonal, matrix, 2 * length, 'BINARY')

print(qubo)

sampler = ExactSolver()
response = sampler.sample(qubo)
print("\nQUBO")
print(response.lowest())