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)
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)
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)
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)
# 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))
dwave_sampler = DWaveSampler(solver={'topology__type': topology}) # To use Advantage QPU # dwave_sampler = LeapHybridSampler(dwave_sampler) # sampler = EmbeddingComposite(dwave_sampler) # computation = KerberosSampler().sample_qubo(quboDict, max_iter=10, convergence=3) # computation = LeapHybridSampler().sample_qubo(quboDict[0],) computation = KerberosSampler().sample_qubo( # quboDict,num_reads=num_reads) computation = sampler.sample_qubo(quboDict, label='Test Topology: {0}, # Nodes: {1}, Num_reads: {2}'.format(topology, NUM_NODES, num_reads), num_reads=num_reads) # Define the workflow iteration = hybrid.RacingBranches( hybrid.InterruptableTabuSampler(), hybrid.EnergyImpactDecomposer(size=5) | hybrid.QPUSubproblemAutoEmbeddingSampler() | hybrid.SplatComposer()) | hybrid.ArgMin() workflow = hybrid.LoopUntilNoImprovement(iteration, convergence=20) bqm = quboDict # Solve the problem # init_state = hybrid.State.from_problem(bqm) # final_state = workflow.run(init_state).result() sampler = HybridSampler(workflow) computation = sampler.sample_qubo(quboDict, label='Hybrid Test Topology: {0}, ' 'Nodes: {1}, ' 'Num_reads: {2}'.format( topology, NUM_NODES, num_reads), num_reads=num_reads)
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 "" # Using dwave-hybrid (elapsed time: 17.1963908672s) # 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... 100 energy num_oc.
H = 0 for i in range(len(arr)): if (i % 10 == 0): #high impact variables H += 1000 * arr[i] * Spin(f'x_{i}') continue H += arr[i] * Spin(f'x_{i}') H *= H print("Compiling...") model = H.compile() bqm = model.to_bqm() print("OK") import hybrid hybrid.logger.setLevel(hybrid.logging.DEBUG) workflow = hybrid.Loop(hybrid.RacingBranches( hybrid.InterruptableSimulatedAnnealingProblemSampler(), hybrid.EnergyImpactDecomposer(size=10, rolling=True, rolling_history=.3) | hybrid.QPUSubproblemAutoEmbeddingSampler(num_reads=2) | hybrid.SplatComposer()) | hybrid.ArgMin(), convergence=3) # not our workflow result = hybrid.KerberosSampler().sample(bqm) hybrid.Unwind(workflow) print("Solution: sample={}".format(result.first)) #hybrid.print_structure(workflow) print("-----------------------") #hybrid.print_counters(workflow)
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.Race( 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}
# https://docs.ocean.dwavesys.com/en/latest/examples/hybrid1.html#hybrid1 import dimod import networkx as nx import random graph = nx.barabasi_albert_graph(100, 3, seed=1) h = {v: 0.0 for v in graph.nodes} J = {edge: random.choice([-1, 1]) for edge in graph.edges} bqm = dimod.BQM(h, J, offset=0, vartype=dimod.SPIN) import hybrid hybrid.logger.setLevel(hybrid.logging.DEBUG) workflow = hybrid.Loop(hybrid.RacingBranches( hybrid.InterruptableTabuSampler(max_time=0), hybrid.EnergyImpactDecomposer(size=100, rolling=True, rolling_history=0.75) | hybrid.QPUSubproblemAutoEmbeddingSampler(num_reads=1) | hybrid.SplatComposer()) | hybrid.ArgMin(), convergence=3) result = hybrid.HybridSampler(workflow).sample(bqm) hybrid.Unwind(workflow) print("Solution: sample={}".format(result.first)) hybrid.print_structure(workflow) print("-----------------------") hybrid.print_counters(workflow)
# quboDict,num_reads=num_reads) computation = sampler.sample_qubo(quboDict, label='Test Topology: {0}, # Nodes: {1}, Num_reads: {2}'.format(topology, NUM_NODES, num_reads), num_reads=num_reads) import time 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()
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: energy={s.samples.first.energy} sample={s.samples.first.sample} """.format(s=solution))
#subproblem = hybrid.EnergyImpactDecomposer(size=50, rolling_history=0.15) subproblem = hybrid.Unwind( hybrid.EnergyImpactDecomposer(size=100, rolling_history=0.15, traversal='bfs')) # QPU #subsampler = hybrid.QPUSubproblemAutoEmbeddingSampler() | hybrid.SplatComposer() qpu_sampler = hybrid.Map( hybrid.QPUSubproblemAutoEmbeddingSampler()) | hybrid.Reduce( hybrid.Lambda(merge_substates)) | hybrid.SplatComposer() rand_sampler = hybrid.Map(hybrid.RandomSubproblemSampler()) | hybrid.Reduce( hybrid.Lambda(merge_substates)) | hybrid.SplatComposer() iteration = hybrid.RacingBranches( hybrid.InterruptableTabuSampler(), subproblem | qpu_sampler) | hybrid.ArgMin() | hybrid.TrackMin(output=True) workflow = hybrid.LoopUntilNoImprovement(iteration, convergence=5) start_t = time.perf_counter() # Convert to dimod sampler and run workflow result = hybrid.HybridSampler(workflow).sample(bqm) elapsed_t = time.perf_counter() - start_t # show execution profile #hybrid.profiling.print_counters(workflow) print("Solution: sample={}".format(result.first)) # doctest: +SKIP #dwave.inspector.show(result) print("Elapsed time: {}".format(elapsed_t))
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.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))
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