예제 #1
0
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.InterruptableTabuSampler(),
        hybrid.EnergyImpactDecomposer(
            size=max_subproblem_size, rolling=True, rolling_history=0.15)
        | hybrid.QPUSubproblemAutoEmbeddingSampler()
        | hybrid.SplatComposer()) | hybrid.ArgMin()
                           | hybrid.TrackMin(output=True),
                           max_iter=max_iter,
                           max_time=max_time,
                           convergence=convergence,
                           terminate=energy_reached)

    return workflow
예제 #2
0
def hybrid_solver():
    workflow = hybrid.LoopUntilNoImprovement(hybrid.RacingBranches(
        hybrid.InterruptableTabuSampler(),
        hybrid.EnergyImpactDecomposer(size=20)
        | hybrid.QPUSubproblemAutoEmbeddingSampler()
        | hybrid.SplatComposer()) | hybrid.ArgMin(),
                                             convergence=3)
    return hybrid.HybridSampler(workflow)
예제 #3
0
def hybrid_solver():
    workflow = hybrid.Loop(hybrid.RacingBranches(
        hybrid.InterruptableTabuSampler(),
        hybrid.EnergyImpactDecomposer(
            size=30, rolling=True, rolling_history=0.75)
        | hybrid.QPUSubproblemAutoEmbeddingSampler()
        | hybrid.SplatComposer()) | hybrid.ArgMin(),
                           convergence=1)
    return hybrid.HybridSampler(workflow)
예제 #4
0
    def test_racing_workflow_with_oracle_subsolver(self):
        workflow = hybrid.LoopUntilNoImprovement(hybrid.RacingBranches(
            hybrid.InterruptableTabuSampler(),
            hybrid.EnergyImpactDecomposer(size=1)
            | HybridSubproblemRunnable(dimod.ExactSolver())
            | hybrid.SplatComposer()) | hybrid.ArgMin(),
                                                 convergence=3)
        state = State.from_sample(min_sample(self.bqm), self.bqm)
        response = workflow.run(state)

        self.assertIsInstance(response, concurrent.futures.Future)
        self.assertEqual(response.result().samples.record[0].energy, -3.0)
예제 #5
0
    def test_hybrid(self):
        import dimod
        import hybrid

        bqm = dimod.BinaryQuadraticModel({}, {'ab': 1, 'bc': -1, 'ca': 1}, 0, dimod.SPIN)

        workflow = hybrid.Loop(hybrid.Race(
            hybrid.InterruptableTabuSampler(),
            hybrid.EnergyImpactDecomposer(size=2)
            | hybrid.SimulatedAnnealingSubproblemSampler()
            | hybrid.SplatComposer()
        ) | hybrid.ArgMin(), convergence=3)

        result = workflow.run(hybrid.State.from_problem(bqm)).result()

        self.assertEqual(result.samples.first.energy, -3.0)
예제 #6
0
    def test_sampling_parameters_filtering(self):
        class Sampler(dimod.ExactSolver):
            """Exact solver that fails if a sampling parameter is provided."""
            parameters = {}

            def sample(self, bqm):
                return super().sample(bqm)

        workflow = hybrid.LoopUntilNoImprovement(hybrid.RacingBranches(
            hybrid.InterruptableTabuSampler(),
            hybrid.EnergyImpactDecomposer(size=1)
            | HybridSubproblemRunnable(Sampler())
            | hybrid.SplatComposer()) | hybrid.ArgMin(),
                                                 convergence=3)
        state = State.from_sample(min_sample(self.bqm), self.bqm)
        response = workflow.run(state)

        self.assertIsInstance(response, concurrent.futures.Future)
        self.assertEqual(response.result().samples.record[0].energy, -3.0)
예제 #7
0
# 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.

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.Race(
    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
print("Solution: sample={.samples.first}".format(solution))
예제 #8
0
        list1, list2 = split_numbers_list(numbers, sample)
        print "list1: {}, sum: {}, list2: {}, sum: {}".format(
            list1, sum(list1), list2, sum(list2))


dwave_sampler = EmbeddingComposite(DWaveSampler())

print "#" * 80
numbers = generate_numbers(
    100)  # generate a list of numbers to be split into equal sums
bqm = to_bqm(numbers)

# Redefine the workflow: a rolling decomposition window
decomposer = hybrid.EnergyImpactDecomposer(size=50, rolling_history=0.15)
sampler = hybrid.QPUSubproblemAutoEmbeddingSampler()
composer = hybrid.SplatComposer()

iteration = hybrid.RacingBranches(decomposer | sampler
                                  | composer) | hybrid.ArgMin()

workflow = hybrid.LoopUntilNoImprovement(iteration, convergence=3)

init_state = hybrid.State.from_problem(bqm)

start = time.time()
final_state = workflow.run(init_state).result()
end = time.time()
print "Using dwave-hybrid (elapsed time: {}s)".format(end - start)
print(final_state.samples)
print_result(final_state.samples)
print ""
예제 #9
0
print("BQM size: {}, subproblem size: {}".format(len(bqm), subproblem_size))
# Classical solvers
#subproblem = hybrid.EnergyImpactDecomposer(size=50, rolling_history=0.15)
#subproblem = hybrid.EnergyImpactDecomposer(size=1024, rolling_history=0.15, traversal="bfs")
# Parallel subproblem
subproblem = hybrid.Unwind(
    #hybrid.EnergyImpactDecomposer(size=subproblem_size, rolling_history=0.15, traversal="bfs")
    hybrid.EnergyImpactDecomposer(size=subproblem_size, rolling_history=0.1))

# QPU
#subsampler = hybrid.QPUSubproblemAutoEmbeddingSampler() | hybrid.SplatComposer()

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

# Define the workflow
# iteration = hybrid.RacingBranches(
#     hybrid.InterruptableTabuSampler(),
#     hybrid.EnergyImpactDecomposer(size=2)
#     | hybrid.QPUSubproblemAutoEmbeddingSampler()
#     | hybrid.SplatComposer()
# ) | hybrid.ArgMin()

#iteration = hybrid.RacingBranches(
iteration = hybrid.Race(
    hybrid.InterruptableTabuSampler(),
    #hybrid.SimulatedAnnealingProblemSampler(),
    subproblem | subsampler) | hybrid.ArgMin()
예제 #10
0
# 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.Race(
        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))
예제 #11
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)
예제 #12
0
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:
    energy={s.samples.first.energy}
    sample={s.samples.first.sample}
""".format(s=solution))
예제 #13
0
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
예제 #14
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.

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
iteration = hybrid.Race(
    hybrid.InterruptableTabuSampler(),
    hybrid.EnergyImpactDecomposer(size=50, rolling=True, rolling_history=0.15)
    | hybrid.QPUSubproblemAutoEmbeddingSampler()
    | hybrid.SplatComposer()) | hybrid.ArgMin() | hybrid.TrackMin(output=True)

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 results
print("Solution: sample={.samples.first}".format(solution))
예제 #15
0
    start_time = time.time()

    # Define the workflow
    iteration = hybrid.RacingBranches(
        # Runs (races) multiple workflows of type Runnable in parallel, stopping all once the first
        # finishes. Returns the results of all, in the specified order.
        hybrid.InterruptableTabuSampler(
        ),  # Tabu algorithm seek of best solutions
        hybrid.EnergyImpactDecomposer(
            size=5
        )  # Selects a subproblem of variables maximally contributing to the
        # problem energy.
        | hybrid.QPUSubproblemAutoEmbeddingSampler(
        )  # A quantum sampler for a subproblem with automated heuristic
        # minor-embedding.
        | hybrid.SplatComposer(
        )  # A composer that overwrites current samples with subproblem samples.
    ) | hybrid.ArgMin()  # Selects the best state from a sequence of States
    workflow = hybrid.LoopUntilNoImprovement(
        iteration, convergence)  # Iterates Runnable for up to max_iter times,
    # or until a state quality metric, defined by the key function, shows no improvement for at least convergence
    # number of iterations.

    # Solve the problem
    init_state = hybrid.State.from_problem(_QUBOdictionary)
    computation = workflow.run(init_state).result()

    # print execution time
    print('Execution time for {0} nodes: {1} milliseconds'.format(
        NUM_NODES, (time.time() - start_time) * 1000))

    # Print results
예제 #16
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))
예제 #17
0
    def solve(self):

        self.n_bins_truth = self._data.x.shape[0]
        self.n_bins_reco = self._data.d.shape[0]

        if not self._data.R.shape[1] == self.n_bins_truth:
            raise Exception(
                "Number of bins at truth level do not match between 1D spectrum (%i) and response matrix (%i)"
                % (self.n_bins_truth, self._data.R.shape[1]))
        if not self._data.R.shape[0] == self.n_bins_reco:
            raise Exception(
                "Number of bins at reco level do not match between 1D spectrum (%i) and response matrix (%i)"
                % (self.n_bins_reco, self._data.R.shape[0]))

        self.convert_to_binary()

        print("INFO: N bins:", self._data.x.shape[0])
        print("INFO: n-bits encoding:", self.rho)

        print("INFO: Signal truth-level x:")
        print(self._data.x)
        print("INFO: pseudo-data b:")
        print(self._data.d)
        print("INFO: Response matrix:")
        print(self._data.R)

        self.Q = self.make_qubo_matrix()
        self._bqm = dimod.BinaryQuadraticModel.from_numpy_matrix(self.Q)

        print("INFO: solving the QUBO model (size=%i)..." % len(self._bqm))

        if self.backend in [Backends.cpu]:
            print("INFO: running on CPU...")
            self._results = dimod.ExactSolver().sample(self._bqm)
            self._status = StatusCode.success

        elif self.backend in [Backends.sim]:
            num_reads = self.solver_parameters['num_reads']
            print("INFO: running on simulated annealer (neal), num_reads=",
                  num_reads)

            sampler = neal.SimulatedAnnealingSampler()
            self._results = sampler.sample(self._bqm,
                                           num_reads=num_reads).aggregate()
            self._status = StatusCode.success

        elif self.backend in [
                Backends.qpu, Backends.qpu_hinoise, Backends.qpu_lonoise,
                Backends.hyb, Backends.qsolv
        ]:
            print("INFO: running on QPU")

            config_file = self.get_config_file()
            self._hardware_sampler = DWaveSampler(config_file=config_file)
            print("INFO: QPU configuration file:", config_file)

            print("INFO: finding optimal minor embedding...")

            n_bits_avg = np.mean(self._encoder.rho)
            thr = 4. / float(self.n_bins_truth)
            n_tries = 5 if n_bits_avg < thr else 10

            J = qubo_quadratic_terms_from_np_array(self.Q)
            embedding = self.find_embedding(J, n_tries)

            print("INFO: creating DWave sampler...")
            sampler = FixedEmbeddingComposite(self._hardware_sampler,
                                              embedding)

            if self.backend in [
                    Backends.qpu, Backends.qpu_hinoise, Backends.qpu_lonoise
            ]:
                print("INFO: Running on QPU")
                params = self.solver_parameters
                self._results = sampler.sample(self._bqm, **params).aggregate()
                self._status = StatusCode.success

            elif self.backend in [Backends.hyb]:
                print("INFO: hybrid execution")
                import hybrid

                num_reads = self.solver_parameters['num_reads']
                # Define the workflow
                # hybrid.EnergyImpactDecomposer(size=len(bqm), rolling_history=0.15)
                iteration = hybrid.RacingBranches(
                    hybrid.InterruptableTabuSampler(),
                    hybrid.EnergyImpactDecomposer(size=len(self._bqm) // 2,
                                                  rolling=True)
                    | hybrid.QPUSubproblemAutoEmbeddingSampler(
                        num_reads=num_reads)
                    | hybrid.SplatComposer()) | hybrid.ArgMin()
                #workflow = hybrid.LoopUntilNoImprovement(iteration, convergence=3)
                workflow = hybrid.Loop(iteration, max_iter=20, convergence=3)

                init_state = hybrid.State.from_problem(self._bqm)
                self._results = workflow.run(init_state).result().samples
                self._status = StatusCode.success

                # show execution profile
                print("INFO: timing:")
                workflow.timers
                hybrid.print_structure(workflow)
                hybrid.profiling.print_counters(workflow)

            elif self.backend in [Backends.qsolv]:
                print("INFO: using QBsolve with FixedEmbeddingComposite")
                self._results = QBSolv().sample_qubo(S,
                                                     solver=sampler,
                                                     solver_limit=5)
                self._status = StatusCode.success

            else:
                raise Exception("ERROR: unknown backend", self.backend)

        print("DEBUG: status =", self._status)
        return self._status