Beispiel #1
0
 def test_basic_operation(self):
     bqm = dimod.BinaryQuadraticModel({}, {
         'ab': 1,
         'bc': 1,
         'ca': 1
     }, 0, dimod.SPIN)
     sampleset = KerberosSampler().sample(bqm,
                                          qpu_sampler=MockDWaveSampler(),
                                          max_subproblem_size=1)
Beispiel #2
0
    def dwave_physical_DW_2000Q_5(self):
        print("\nD-wave quantum annealer....")
        from dwave.system import DWaveSampler, FixedEmbeddingComposite
        from dwave.embedding.chimera import find_clique_embedding

        qpu = DWaveSampler(token=self.token,
                           endpoint=self.endpoint,
                           solver=dict(name='DW_2000Q_5'),
                           auto_scale=False)
        self.title = "D-Wave Quantum Annealer"

        embedding = find_clique_embedding(
            self.bqm.variables,
            16,
            16,
            4,  # size of the chimera lattice
            target_edges=qpu.edgelist)

        qpu_sampler = FixedEmbeddingComposite(qpu, embedding)

        print("Maximum chain length for minor embedding is {}.".format(
            max(len(x) for x in embedding.values())))

        from hybrid.reference.kerberos import KerberosSampler
        kerberos_sampler = KerberosSampler()

        selected_features = np.zeros((len(self.features), len(self.features)))
        for k in range(1, len(self.features) + 1):
            print("Submitting for k={}".format(k))
            kbqm = dimod.generators.combinations(self.features, k, strength=6)
            kbqm.update(self.bqm)
            kbqm.normalize()

            best = kerberos_sampler.sample(kbqm,
                                           qpu_sampler=qpu_sampler,
                                           num_reads=10,
                                           max_iter=1).first.sample

            for fi, f in enumerate(self.features):
                selected_features[k - 1, fi] = best[f]
        if self.is_notebook:
            from helpers.draw import plot_feature_selection
            plot_feature_selection(self.features, selected_features)
Beispiel #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()
    return solver
Beispiel #4
0
def solve(grid, use_dwave=False, max_iter=10, convergence=3):
    clues = make_clues(grid)
    G = make_sudoku_graph(clues)
    if use_dwave:
        coloring = dnx.min_vertex_coloring(G,
                                           sampler=KerberosSampler(),
                                           chromatic_lb=9,
                                           chromatic_ub=9,
                                           max_iter=max_iter,
                                           convergence=convergence)
    else:
        coloring = nx.coloring.greedy_color(G, 'saturation_largest_first')
    solution = decode(coloring, clues)
    disp(solution)
    print('Cost: %d\n' % cost(solution))
Beispiel #5
0
    def get_sampler(self, profile, solver):
        "Return a dimod.Sampler object and associated solver information."
        # Handle built-in software samplers as special cases.
        info = {}
        if solver != None:
            info["solver_name"] = solver
        if solver == "exact":
            return ExactSolver(), info, {}
        elif solver == "neal":
            return SimulatedAnnealingSampler(), info, {}
        elif solver == "tabu":
            return TabuSampler(), info, {}
        elif solver == "kerberos" or (solver != None
                                      and solver[:9] == "kerberos,"):
            base_sampler = KerberosSampler()
            try:
                sub_sampler_name = solver.split(",")[1]
            except IndexError:
                sub_sampler_name = None
            sub_sampler, sub_info, params = self.get_sampler_from_config(
                profile, sub_sampler_name, "qpu")
            info.update(self._recursive_properties(sub_sampler))
            info["solver_name"] = "kerberos + %s" % sub_info["solver_name"]
            params["qpu_sampler"] = sub_sampler
            return base_sampler, info, params
        elif solver == "qbsolv" or (solver != None
                                    and solver[:7] == "qbsolv,"):
            base_sampler = QBSolv()
            try:
                sub_sampler_name = solver.split(",")[1]
            except IndexError:
                sub_sampler_name = None
            sub_sampler, sub_info, params = self.get_sampler(
                profile, sub_sampler_name)
            if getattr(sub_sampler, "structure", None) != None:
                sub_sampler = EmbeddingComposite(sub_sampler)
            info.update(self._recursive_properties(sub_sampler))
            info["solver_name"] = "QBSolv + %s" % sub_info["solver_name"]
            params["solver"] = sub_sampler
            return base_sampler, info, params

        # In the common case, read the configuration file, either the
        # default or the one named by the DWAVE_CONFIG_FILE environment
        # variable.
        return self.get_sampler_from_config(profile, solver)
Beispiel #6
0
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import sys

import dimod
from hybrid.reference.kerberos import KerberosSampler

problem = sys.argv[1]
with open(problem) as fp:
    bqm = dimod.BinaryQuadraticModel.from_coo(fp)

energy_threshold = None
if len(sys.argv) > 2:
    energy_threshold = float(sys.argv[2])

solution = KerberosSampler().sample(bqm,
                                    max_iter=10,
                                    convergence=3,
                                    energy_threshold=energy_threshold)

print("Solution: {!r}".format(solution.record))
Beispiel #7
0
import networkx as nx
import dwave_networkx as dnx
from hybrid.reference.kerberos import KerberosSampler
import matplotlib.pyplot as plt

G = nx.read_adjlist('usa.adj', delimiter=',')
coloring = dnx.min_vertex_coloring(G,
                                   sampler=KerberosSampler(),
                                   chromatic_ub=4,
                                   max_iter=10,
                                   convergence=3)
set(coloring.values())
node_colors = [coloring.get(node) for node in G.nodes()]
if dnx.is_vertex_coloring(
        G, coloring):  # adjust the next line if using a different map
    nx.draw(G,
            pos=nx.shell_layout(
                G,
                nlist=[list(G.nodes)[x:x + 10]
                       for x in range(0, 50, 10)] + [[list(G.nodes)[50]]]),
            with_labels=True,
            node_color=node_colors,
            node_size=400,
            cmap=plt.cm.rainbow)
plt.show()
Beispiel #8
0
 def getSampler(self):
     return AutoEmbeddingComposite(KerberosSampler())
Beispiel #9
0
# Apply one color constraint
for p in provinces:
    csp.add_constraint(select_one, {p.red, p.green, p.blue, p.yellow})

# Apply no color sharing between neighbours
for x, y in neighbours:
    csp.add_constraint(not_both, {x.red, y.red})
    csp.add_constraint(not_both, {x.green, y.green})
    csp.add_constraint(not_both, {x.blue, y.blue})
    csp.add_constraint(not_both, {x.yellow, y.yellow})

# Combine constraints to form a BQM
bqm = dwavebinarycsp.stitch(csp)

# Solve BQM
solution = KerberosSampler().sample(bqm)
best_solution = solution.first.sample
print("Solution: ", best_solution)

# Verify
is_correct = csp.check(best_solution)
print("Does solution satisfy our constraints? {}".format(is_correct))

# Visualize the solution
# Note: The following is purely for visualizing the output and is not necessary
# for the demo.

# Hard code node positions to be reminiscent of the map of Canada
node_positions = {
    "bc": (0, 1),
    "ab": (2, 1),
Beispiel #10
0
import networkx as nx
import dwave_networkx as dnx
from hybrid.reference.kerberos import KerberosSampler
import matplotlib.pyplot as plt

G = nx.read_adjlist('usa.adj', delimiter=',')
coloring = dnx.min_vertex_coloring(G, sampler = KerberosSampler(), chromatic_ub=4, max_iter=10, convergence=3)
node_colors = [coloring.get(node) for node in G.nodes()]
if dnx.is_vertex_coloring(G, coloring):  # adjust the next line if using a different map
  nx.draw(G, pos=nx.shell_layout(G, nlist = [list(G.nodes)[x:x+10] for x in range(0, 50, 10)] + [[list(G.nodes)[50]]]), with_labels=True, node_color=node_colors, node_size=400, cmap=plt.cm.rainbow)
plt.show()

for x, y in neighbours:
    csp.add_constraint(not_both, {x.red, y.red})
    csp.add_constraint(not_both, {x.green, y.green})
    csp.add_constraint(not_both, {x.blue, y.blue})
    csp.add_constraint(not_both, {x.yellow, y.yellow})

# In[ ]:

bqm = dwavebinarycsp.stitch(csp)

# In[ ]:

print("Sampling")
#response = sampler.sample(bqm, num_reads=1000)
response = KerberosSampler().sample(bqm)
print("Done")

# In[ ]:

print(response)

# In[ ]:

print(csp.check(response.first.sample))

# In[ ]:

nodes = [p.name for p in provinces]

# In[ ]:
    def kerberos_solver(self, **kwargs):
        """Run Tabu search, Simulated annealing and QPU subproblem sampling (for
            high energy impact problem variables) in parallel and return the best
            samples.

            Sampling Args:

                bqm (:obj:`~dimod.BinaryQuadraticModel`):
                    Binary quadratic model to be sampled from.

                init_sample (:class:`~dimod.SampleSet`, callable, ``None``):
                    Initial sample set (or sample generator) used for each "read".
                    Use a random sample for each read by default.

                num_reads (int):
                    Number of reads. Each sample is the result of a single run of the
                    hybrid algorithm.

            Termination Criteria Args:

                max_iter (int):
                    Number of iterations in the hybrid algorithm.

                max_time (float/None, optional, default=None):
                    Wall clock runtime termination criterion. Unlimited by default.

                convergence (int):
                    Number of iterations with no improvement that terminates sampling.

                energy_threshold (float, optional):
                    Terminate when this energy threshold is surpassed. Check is
                    performed at the end of each iteration.

            Simulated Annealing Parameters:

                sa_reads (int):
                    Number of reads in the simulated annealing branch.

                sa_sweeps (int):
                    Number of sweeps in the simulated annealing branch.

            Tabu Search Parameters:

                tabu_timeout (int):
                    Timeout for non-interruptable operation of tabu search (time in
                    milliseconds).

            QPU Sampling Parameters:

                qpu_reads (int):
                    Number of reads in the QPU branch.

                qpu_sampler (:class:`dimod.Sampler`, optional, default=DWaveSampler()):
                    Quantum sampler such as a D-Wave system.

                qpu_params (dict):
                    Dictionary of keyword arguments with values that will be used
                    on every call of the QPU sampler.

                max_subproblem_size (int):
                    Maximum size of the subproblem selected in the QPU branch.

                Returns:
                    :obj:`~dimod.SampleSet`: A `dimod` :obj:`.~dimod.SampleSet` object.

                """
        response = KerberosSampler().sample(self.bqm, **kwargs)
        solution = np.array([int(i) for i in response.first[0].values()])
        self.current_solution = self.solution_energy(solution), solution
        return self.current_solution
#!/usr/bin/env python

# Copyright 2018 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import sys

import dimod
from hybrid.reference.kerberos import KerberosSampler

problem = sys.argv[1]
with open(problem) as fp:
    bqm = dimod.BinaryQuadraticModel.from_coo(fp)

solution = KerberosSampler().sample(bqm, max_iter=10, convergence=3)

print("Solution: {!r}".format(solution.record))
Beispiel #14
0
print("Added", N, "column constraints to Q matrix.")

for u in range(N):
    for v in range(N):
        if u != v:
            for j in range(N):
                Q[(x(u, j), x(v, (j + 1) % N))] += D[u][v]

print("Objective function added.")

Q = {k: v for k, v in Q.items() if v != 0}
print("Q matrix reduced to", len(Q), "entries.")

start = time.time()
resp = KerberosSampler().sample_qubo(Q)
end = time.time()
time_KS = end - start

print("KerberosSampler call complete using", time_KS, "seconds.")

start = time.time()
# First solution is the lowest energy solution found
sample = next(iter(resp))

# Display energy for best solution found
print("Energy: ", next(iter(resp.data())).energy)

# Print route for solution found
route = [-1] * N
for node in sample:
Beispiel #15
0
# Apply one color constraint
for p in provinces:
    csp.add_constraint(select_one, {p.red, p.green, p.blue, p.yellow})

# Apply no color sharing between neighbours
for x, y in neighbours:
    csp.add_constraint(not_both, {x.red, y.red})
    csp.add_constraint(not_both, {x.green, y.green})
    csp.add_constraint(not_both, {x.blue, y.blue})
    csp.add_constraint(not_both, {x.yellow, y.yellow})

# Combine constraints to form a BQM
bqm = dwavebinarycsp.stitch(csp)

# Solve BQM
solution = KerberosSampler().sample(
    bqm, qpu_params={'label': 'Example - Map Coloring'})
best_solution = solution.first.sample
print("Solution: ", best_solution)

# Verify
is_correct = csp.check(best_solution)
print("Does solution satisfy our constraints? {}".format(is_correct))

# Visualize the solution
# Note: The following is purely for visualizing the output and is not necessary
# for the demo.

# Hard code node positions to be reminiscent of the map of Canada
node_positions = {
    "bc": (0, 1),
    "ab": (2, 1),