コード例 #1
0
ファイル: qbsolv.py プロジェクト: rickyHong/dwave-hybrid-repl
def SimplifiedQbsolv(max_iter=10,
                     max_time=None,
                     convergence=3,
                     energy_threshold=None,
                     max_subproblem_size=30):
    """Races a Tabu solver and a QPU-based sampler of flip-energy-impact induced
    subproblems.

    For arguments description see: :class:`~hybrid.reference.kerberos.Kerberos`.
    """

    energy_reached = None
    if energy_threshold is not None:
        energy_reached = lambda en: en <= energy_threshold

    workflow = hybrid.Loop(hybrid.Race(
        hybrid.Identity(), hybrid.InterruptableTabuSampler(),
        hybrid.EnergyImpactDecomposer(
            size=max_subproblem_size, rolling=True, rolling_history=0.15)
        | hybrid.QPUSubproblemAutoEmbeddingSampler()
        | hybrid.SplatComposer()) | hybrid.ArgMin(),
                           max_iter=max_iter,
                           max_time=max_time,
                           convergence=convergence,
                           terminate=energy_reached)

    return workflow
コード例 #2
0
# 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
import hybrid

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

# define the workflow
workflow = hybrid.Loop(hybrid.RacingBranches(
    hybrid.Identity(), hybrid.InterruptableTabuSampler(),
    hybrid.EnergyImpactDecomposer(size=50, rolling=True, traversal='bfs')
    | hybrid.QPUSubproblemAutoEmbeddingSampler()
    | hybrid.SplatComposer()) | hybrid.ArgMin(),
                       convergence=3)

# create a dimod sampler that runs the workflow and sample
result = hybrid.HybridSampler(workflow).sample(bqm)

# show results
print("Solution: sample={.first}".format(result))
コード例 #3
0
problem = sys.argv[1]
with open(problem) as fp:
    bqm = dimod.BinaryQuadraticModel.from_coo(fp)

# construct a Dialectic Search workflow
generate_antithesis = (hybrid.IdentityDecomposer()
                       | hybrid.RandomSubproblemSampler()
                       | hybrid.SplatComposer()
                       | hybrid.TabuProblemSampler())

generate_synthesis = (hybrid.GreedyPathMerge() | hybrid.TabuProblemSampler())

tracker = hybrid.TrackMin()

local_update = hybrid.LoopWhileNoImprovement(
    hybrid.Parallel(hybrid.Identity(), generate_antithesis)
    | generate_synthesis | tracker,
    max_tries=10)

global_update = hybrid.Loop(generate_antithesis | local_update, max_iter=10)

# run the workflow
init_state = hybrid.State.from_sample(hybrid.min_sample(bqm), bqm)
final_state = global_update.run(init_state).result()

# show execution profile
hybrid.profiling.print_counters(global_update)

# show results
print("Solution: sample={.samples.first}".format(tracker.best))
コード例 #4
0
from __future__ import print_function

import sys
import operator

import dimod
import hybrid

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

# construct a workflow that races Simulated Annealing against SA/Tabu on a subproblem
iteration = hybrid.RacingBranches(
    hybrid.Identity(), hybrid.SimulatedAnnealingProblemSampler(),
    hybrid.EnergyImpactDecomposer(size=50)
    | hybrid.RacingBranches(
        hybrid.SimulatedAnnealingSubproblemSampler(num_sweeps=1000),
        hybrid.TabuSubproblemSampler(tenure=20, timeout=10))
    | hybrid.ArgMin('subsamples.first.energy')
    | hybrid.SplatComposer()) | hybrid.ArgMin('samples.first.energy')
main = hybrid.Loop(iteration, max_iter=10, convergence=3)

# run the workflow
init_state = hybrid.State.from_sample(hybrid.utils.min_sample(bqm), bqm)
solution = main.run(init_state).result()

# show results
print("""
Solution:
コード例 #5
0
ファイル: kerberos.py プロジェクト: quantumahesh/dwave-hybrid
def Kerberos(max_iter=100,
             max_time=None,
             convergence=3,
             energy_threshold=None,
             sa_reads=1,
             sa_sweeps=10000,
             tabu_timeout=500,
             qpu_reads=100,
             qpu_sampler=None,
             qpu_params=None,
             max_subproblem_size=50):
    """An opinionated hybrid asynchronous decomposition sampler for problems of
    arbitrary structure and size. Runs Tabu search, Simulated annealing and QPU
    subproblem sampling (for high energy impact problem variables) in parallel
    and returns the best samples.

    Kerberos workflow is used by :class:`KerberosSampler`.

    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:
        Workflow (:class:`~hybrid.core.Runnable` instance).

    """

    energy_reached = None
    if energy_threshold is not None:
        energy_reached = lambda en: en <= energy_threshold

    iteration = hybrid.Race(
        hybrid.Identity(),
        hybrid.InterruptableTabuSampler(timeout=tabu_timeout),
        hybrid.InterruptableSimulatedAnnealingProblemSampler(
            num_reads=sa_reads, num_sweeps=sa_sweeps),
        hybrid.EnergyImpactDecomposer(size=max_subproblem_size,
                                      rolling=True,
                                      rolling_history=0.3,
                                      traversal='bfs')
        | hybrid.QPUSubproblemAutoEmbeddingSampler(num_reads=qpu_reads,
                                                   qpu_sampler=qpu_sampler,
                                                   qpu_params=qpu_params)
        | hybrid.SplatComposer()) | hybrid.ArgMin()

    workflow = hybrid.Loop(iteration,
                           max_iter=max_iter,
                           max_time=max_time,
                           convergence=convergence,
                           terminate=energy_reached)

    return workflow
コード例 #6
0
    a, b = substates
    return a.updated(
        subsamples=hybrid.hstack_samplesets(a.subsamples, b.subsamples))


subproblems = hybrid.Unwind(
    hybrid.EnergyImpactDecomposer(size=50, rolling_history=0.15))

qpu = hybrid.Map(hybrid.QPUSubproblemAutoEmbeddingSampler()) | hybrid.Reduce(
    hybrid.Lambda(merge_substates)) | hybrid.SplatComposer()

random = hybrid.Map(hybrid.RandomSubproblemSampler()) | hybrid.Reduce(
    hybrid.Lambda(merge_substates)) | hybrid.SplatComposer()

subsampler = hybrid.Parallel(qpu, random, endomorphic=False) | hybrid.ArgMin()

iteration = hybrid.Race(hybrid.Identity(), hybrid.InterruptableTabuSampler(),
                        subproblems | subsampler) | hybrid.ArgMin()

main = hybrid.Loop(iteration, max_iter=10, convergence=3)

# run the workflow
init_state = hybrid.State.from_sample(hybrid.min_sample(bqm), bqm)
solution = main.run(init_state).result()

# show execution profile
hybrid.profiling.print_counters(main)

# show results
print("Solution: sample={.samples.first}".format(solution))
コード例 #7
0
import sys

import dimod
import hybrid


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


# run Tabu in parallel with QPU, but post-process QPU samples with very short Tabu
iteration = hybrid.RacingBranches(
    hybrid.Identity(),
    hybrid.InterruptableTabuSampler(),
    hybrid.EnergyImpactDecomposer(size=50)
    | hybrid.QPUSubproblemAutoEmbeddingSampler(num_reads=100)
    | hybrid.SplatComposer()
    | hybrid.TabuProblemSampler(timeout=1)
) | hybrid.ArgMin()

main = hybrid.Loop(iteration, max_iter=10, convergence=3)


# run the workflow
init_state = hybrid.State.from_sample(hybrid.utils.min_sample(bqm), bqm)
solution = main.run(init_state).result()

# show results
コード例 #8
0
    def sample(self,
               bqm,
               init_sample=None,
               max_iter=100,
               convergence=3,
               num_reads=1,
               sa_reads=1,
               sa_sweeps=10000,
               tabu_timeout=500,
               qpu_reads=100,
               qpu_sampler=None,
               qpu_params=None,
               max_subproblem_size=50,
               energy_threshold=None):
        """Run Tabu search, Simulated annealing and QPU subproblem sampling (for
        high energy impact problem variables) in parallel and return the best
        samples.

        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.

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

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

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

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

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

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

            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.

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

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

        """

        if callable(init_sample):
            init_state_gen = lambda: hybrid.State.from_sample(
                init_sample(), bqm)
        elif init_sample is None:
            init_state_gen = lambda: hybrid.State.from_sample(
                hybrid.random_sample(bqm), bqm)
        elif isinstance(init_sample, dimod.SampleSet):
            init_state_gen = lambda: hybrid.State.from_sample(init_sample, bqm)
        else:
            raise TypeError(
                "'init_sample' should be a SampleSet or a SampleSet generator")

        subproblem_size = min(len(bqm), max_subproblem_size)

        energy_reached = None
        if energy_threshold is not None:
            energy_reached = lambda en: en <= energy_threshold

        iteration = hybrid.Race(
            hybrid.Identity(),
            hybrid.InterruptableTabuSampler(timeout=tabu_timeout),
            hybrid.InterruptableSimulatedAnnealingProblemSampler(
                num_reads=sa_reads, num_sweeps=sa_sweeps),
            hybrid.EnergyImpactDecomposer(size=subproblem_size,
                                          rolling=True,
                                          rolling_history=0.3,
                                          traversal='bfs')
            | hybrid.QPUSubproblemAutoEmbeddingSampler(num_reads=qpu_reads,
                                                       qpu_sampler=qpu_sampler,
                                                       qpu_params=qpu_params)
            | hybrid.SplatComposer(),
        ) | hybrid.ArgMin()

        self.runnable = hybrid.Loop(iteration,
                                    max_iter=max_iter,
                                    convergence=convergence,
                                    terminate=energy_reached)

        samples = []
        energies = []
        for _ in range(num_reads):
            init_state = init_state_gen()
            final_state = self.runnable.run(init_state)
            # the best sample from each run is one "read"
            ss = final_state.result().samples
            ss.change_vartype(bqm.vartype, inplace=True)
            samples.append(ss.first.sample)
            energies.append(ss.first.energy)

        return dimod.SampleSet.from_samples(samples,
                                            vartype=bqm.vartype,
                                            energy=energies)