コード例 #1
0
    def test_max_cut(self):
        sampler = EmbeddingComposite(MockDWaveSampler())

        m = 2
        n = 2
        t = 2

        hoff = 2 * t
        voff = n * hoff
        mi = m * voff
        ni = n * hoff

        edges = []

        # tile edges
        edges.extend((k0, k1) for i in range(0, ni, hoff)
                     for j in range(i, mi, voff) for k0 in range(j, j + t)
                     for k1 in range(j + t, j + 2 * t))
        # horizontal edges
        edges.extend((k, k + hoff) for i in range(t, 2 * t)
                     for j in range(i, ni - hoff, hoff)
                     for k in range(j, mi, voff))
        # vertical edges
        edges.extend((k, k + voff) for i in range(t)
                     for j in range(i, ni, hoff)
                     for k in range(j, mi - voff, voff))

        J = {edge: 1 for edge in edges}
        h = {v: 0 for v in set().union(*J)}

        response = sampler.sample_ising(h, J)
コード例 #2
0
ファイル: demo.py プロジェクト: whigg/QNNAnnealer
def start_annealing(layers: list, input_data, output_data, lagrange_propagation=1, qpu=False, stitch_kwargs=None):
    if qpu:
        sampler = EmbeddingComposite(
            DWaveSampler(solver={'topology__type': 'pegasus', 'qpu': True}))
    else:
        sampler = tabu.TabuSampler()

    bqm = get_qnn_bqm(layers, input_data, output_data, lagrange_propagation, stitch_kwargs)

    # Check elements in the BQM
    # for q in bqm.linear:
    #     if bqm.linear[q] != -1:
    #         print(q)
    # for q in bqm.quadratic:
    #     if bqm.quadratic[q] != 2:
    #         print(q, bqm.quadratic[q])

    # Run BQM and get the solution and the energy
    sampleset = sampler.sample(bqm, num_reads=1000)
    solution1 = sampleset.first.sample
    energy1 = sampleset.first.energy

    print("Nodes chosen ('layer_n.o'): ")
    pprint(solution1)
    print("Solution energy: ", energy1)
    def run_dwave(self, H, sym):
        """Run a quantum annealing protocol using D-Wave's devices.

        Args:
            H (symbol): Hamiltonian that encodes the solution of a problem.
            sys (tuple): symbols that make up the Hamiltonian.

        Returns:
            response: object that contains the details of the experiment.

        """
        chainstrength = self.chainstrength
        numruns, T = self.numruns, self.T
        symbol_num = self.get_symbol_num(sym)
        Q, constant = self.symbolic_to_dwave(H, symbol_num)
        model = dimod.BinaryQuadraticModel.from_qubo(Q, offset = constant)

        if not chainstrength:
            chainstrength = 0
            for i in Q.values():
                chainstrength += abs(i)
            chainstrength *= 3/len(Q)
            #print(f'Automatic chain strength: {chainstrength}\n')
        #else:
            #print(f'Chosen chain strength: {chainstrength}\n')

        sampler = EmbeddingComposite(DWaveSampler())
        response = sampler.sample(model, chain_strength=chainstrength, num_reads=numruns, annealing_time=T, answer_mode='histogram')
        return response
コード例 #4
0
    def __init__(self,
                 num_reads=100,
                 qpu_sampler=None,
                 anneal_schedule=None,
                 **runopts):
        super(ReverseAnnealingAutoEmbeddingSampler, self).__init__(**runopts)

        self.num_reads = num_reads

        if anneal_schedule is None:
            anneal_schedule = [[0, 1], [0.5, 0.5], [1, 1]]
        self.anneal_schedule = anneal_schedule

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler(solver={
                'max_anneal_schedule_points__gte':
                len(self.anneal_schedule)
            })

        # validate schedule, raising `ValueError` on invalid schedule or
        # `RuntimeError` if anneal schedule not supported by QPU (this could
        # happen only if user provided the `qpu_sampler`)
        qpu_sampler.validate_anneal_schedule(anneal_schedule)

        # convert the structured sampler to unstructured
        if isinstance(qpu_sampler, dimod.Structured):
            self.sampler = EmbeddingComposite(qpu_sampler)
        else:
            self.sampler = qpu_sampler
コード例 #5
0
    def test_return_embedding(self):
        nodelist = [0, 1, 2]
        edgelist = [(0, 1), (1, 2), (0, 2)]

        sampler = EmbeddingComposite(
            dimod.StructureComposite(dimod.NullSampler(), nodelist, edgelist))

        sampleset = sampler.sample_ising({'a': -1}, {'ac': 1},
                                         return_embedding=True)

        self.assertIn('embedding', sampleset.info['embedding_context'])
        embedding = sampleset.info['embedding_context']['embedding']
        self.assertEqual(set(embedding), {'a', 'c'})

        self.assertIn('chain_break_method',
                      sampleset.info['embedding_context'])
        self.assertEqual(
            sampleset.info['embedding_context']['chain_break_method'],
            'majority_vote')  # the default

        self.assertIn('embedding_parameters',
                      sampleset.info['embedding_context'])
        self.assertEqual(
            sampleset.info['embedding_context']['embedding_parameters'],
            {})  # the default

        self.assertIn('chain_strength', sampleset.info['embedding_context'])
        self.assertEqual(sampleset.info['embedding_context']['chain_strength'],
                         1.0)  # the default

        # default False
        sampleset = sampler.sample_ising({'a': -1}, {'ac': 1})
        self.assertNotIn('embedding_context', sampleset.info)
コード例 #6
0
    def test_return_embedding_as_class_variable(self):
        nodelist = [0, 1, 2]
        edgelist = [(0, 1), (1, 2), (0, 2)]

        sampler = EmbeddingComposite(
            dimod.StructureComposite(dimod.NullSampler(), nodelist, edgelist))

        # temporarily change return_embedding_default
        EmbeddingComposite.return_embedding_default = True

        sampleset = sampler.sample_ising({'a': -1}, {'ac': 1})

        self.assertIn('embedding', sampleset.info['embedding_context'])
        embedding = sampleset.info['embedding_context']['embedding']
        self.assertEqual(set(embedding), {'a', 'c'})

        self.assertIn('chain_break_method',
                      sampleset.info['embedding_context'])
        self.assertEqual(
            sampleset.info['embedding_context']['chain_break_method'],
            'majority_vote')  # the default

        self.assertIn('embedding_parameters',
                      sampleset.info['embedding_context'])
        self.assertEqual(
            sampleset.info['embedding_context']['embedding_parameters'],
            {})  # the default

        self.assertIn('chain_strength', sampleset.info['embedding_context'])
        self.assertEqual(sampleset.info['embedding_context']['chain_strength'],
                         1.414)  # the default

        # restore the default
        EmbeddingComposite.return_embedding_default = False
コード例 #7
0
    def test_singleton_variables(self):
        sampler = EmbeddingComposite(MockDWaveSampler())

        h = {0: -1., 4: 2}
        J = {}

        response = sampler.sample_ising(h, J)

        # nothing failed and we got at least one response back
        self.assertGreaterEqual(len(response), 1)
コード例 #8
0
ファイル: task.py プロジェクト: Loag/d-wave-testing
    def run_data(self, chain_strength=5, num_reads=100):
        if self.input_data == None:
            raise Exception("You must include a dataset, use set_data")

        print(f"Using Chain Strength: {chain_strength}")
        print(f"Number of reads: {num_reads}")

        self.result = EmbeddingComposite(self.sampler).sample_qubo(
            self.input_data,
            chain_strength=chain_strength,
            num_reads=num_reads)
コード例 #9
0
def sample_on_dwave(Q, Quantum=False):
    bqm = dimod.BinaryQuadraticModel.from_numpy_matrix(Q)

    if Quantum:
        # Real
        sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
        return sampler.sample(bqm, chain_strength=chstr)

    # Simulated
    sampler = neal.SimulatedAnnealingSampler()
    return sampler.sample(bqm=bqm, num_reads=numr)
コード例 #10
0
    def test_embedding_parameters_sample(self):
        child = dimod.StructureComposite(dimod.NullSampler(), [0, 1], [(0, 1)])

        def my_find_embedding(S, T, a):
            assert a == -1
            return {v: [v] for v in set().union(*S)}

        sampler = EmbeddingComposite(child, find_embedding=my_find_embedding)

        # nothing breaks
        sampler.sample_ising({0: -1}, {}, embedding_parameters={'a': -1})
コード例 #11
0
    def test_find_embedding_kwarg(self):
        child = dimod.StructureComposite(dimod.NullSampler(), [0, 1], [(0, 1)])

        def my_find_embedding(S, T):
            # does nothing
            return {v: [v] for v in set().union(*S)}

        sampler = EmbeddingComposite(child, find_embedding=my_find_embedding)

        # nothing breaks
        sampler.sample_ising({0: -1}, {})
コード例 #12
0
    def test_warnings(self):
        G = dnx.chimera_graph(12)

        sampler = EmbeddingComposite(
            dimod.StructureComposite(dimod.RandomSampler(), G.nodes, G.edges))

        # this will need chains lengths > 7
        J = {uv: -1 for uv in itertools.combinations(range(40), 2)}

        ss = sampler.sample_ising({}, J, warnings='SAVE')

        self.assertIn('warnings', ss.info)
コード例 #13
0
    def test_chain_break_method_customization(self):
        sampler = EmbeddingComposite(MockDWaveSampler())

        with mock.patch('dwave.system.composites.embedding.unembed_sampleset'
                        ) as mock_unembed:
            sampler.sample_ising({'a': 1}, {},
                                 chain_break_method=chain_breaks.discard)

            # assert chain_break_method propagated to unembed_sampleset
            __, kwargs = mock_unembed.call_args
            self.assertEqual(kwargs['chain_break_method'],
                             chain_breaks.discard)
コード例 #14
0
    def _create_composite(self, embedding_parameters=None):
        if (self._endpoint is not None) and (self._token is not None):
            sampler = DWaveSampler(endpoint=self._endpoint, token=self._token, solver=self._solver)
        else:
            sampler = DWaveSampler(solver=self._solver)

        if (embedding_parameters is not None) and isinstance(embedding_parameters, dict):
            solver = EmbeddingComposite(sampler, embedding_parameters=embedding_parameters)
        else:
            solver = EmbeddingComposite(sampler)

        return solver
コード例 #15
0
def quantumOptim(h,J):
    h,J=convertCompatible(h,J)
    sampler = EmbeddingComposite(DWaveSampler(endpoint='https://cloud.dwavesys.com/sapi', token='[EnterTokenHere]', solver='DW_2000Q_2_1'))
    response = sampler.sample_ising(h,J,num_reads=1000)

    Q_energy=[]
    Q_sigma=[]

    for datum in response.data(['sample', 'energy']):
        Q_energy.append(datum.energy)
        Q_sigma.append(list(datum.sample.values()))
      
    return Q_sigma[0],Q_energy[0]
コード例 #16
0
ファイル: samplers.py プロジェクト: sajidsaleem/dwave-hybrid
    def __init__(self, num_reads=100, qpu_sampler=None):
        super(QPUSubproblemAutoEmbeddingSampler, self).__init__()

        self.num_reads = num_reads

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler()

        # convert the structured sampler to unstructured
        if isinstance(qpu_sampler, dimod.Structured):
            self.sampler = EmbeddingComposite(qpu_sampler)
        else:
            self.sampler = qpu_sampler
コード例 #17
0
ファイル: main.py プロジェクト: igres26/exact-cover-dwave
def main(nqubits, instance, T, chainstrength, numruns, greedy, inspect):
    """

    Args:
        nqubits (int): number of qubits for the file that contains the
            information of an Exact Cover instance.
        instance (int): intance used for the desired number of qubits.
        T (float): 
        

    Returns:
        
    """
    control, solution, clauses = functions.read_file(nqubits, instance)
    nqubits = int(control[0])
    times = functions.times(nqubits, clauses)
    sh, smap = functions.h_problem(nqubits, clauses)
    Q, constant = functions.symbolic_to_dwave(sh, smap)
    

    model = dimod.BinaryQuadraticModel.from_qubo(Q, offset = 0.0)
    if not chainstrength:
        chainstrength = dwave.embedding.chain_strength.uniform_torque_compensation(model)
        print(f'Automatic chain strength: {chainstrength}\n')
    else:
        print(f'Chosen chain strength: {chainstrength}\n')

    if solution:
        print(f'Target solution that solves the problem: {" ".join(solution)}\n')

    sampler = EmbeddingComposite(DWaveSampler())
    if greedy:
        solver_greedy = SteepestDescentSolver()
        sampleset = sampler.sample(model, chain_strength=chainstrength, num_reads=numruns, annealing_time=T, answer_mode='raw')
        response = solver_greedy.sample(model, initial_states=sampleset)
    else:
        response = sampler.sample(model, chain_strength=chainstrength, num_reads=numruns, annealing_time=T, answer_mode='histogram')
    
    
    best_sample = response.record.sample[0]
    best_energy = response.record.energy[0]
    print(f'Best result found: {best_sample}\n')
    print(f'With energy: {best_energy+constant}\n')
    good_samples = response.record.sample[:min(len(response.record.sample), nqubits)]
    good_energies = response.record.energy[:min(len(response.record.energy), nqubits)]
    print(f'The best {len(good_samples)} samples found in the evolution are:\n')
    for i in range(len(good_samples)):
        print(f'Sample: {good_samples[i]}    with energy: {good_energies[i]+constant}\n')

    if inspect:
        dwave.inspector.show(response)
コード例 #18
0
def num_of_errors_in_chain_strengths(qpu=False):
    jobs = {
        "1": [(0, 2), (1, 1), (2, 1)],
        "2": [(1, 1), (0, 1), (3, 2)],
        "3": [(2, 1), (3, 1), (1, 1)]
    }

    strengths = (0.5, 1, 1.5, 1.8, 2.0, 2.1, 2.3, 2.5, 3.0, 3.5, 4.0)
    errors = defaultdict(list)
    for strength in strengths:
        for i in range(12):
            print("tick " + str(strength) + " " + str(i))
            try:
                bqm = get_jss_bqm(jobs,
                                  8,
                                  stitch_kwargs={'min_classical_gap': 2.0})
                if qpu:
                    sampler = EmbeddingComposite(
                        DWaveSampler(solver={'qpu': True}))
                    sampleset = sampler.sample(bqm,
                                               chain_strength=strength,
                                               num_reads=1000)
                else:
                    sampler = neal.SimulatedAnnealingSampler()
                    sampleset = sampler.sample(bqm, num_reads=1000)
                sol_dict = printResults(sampleset, jobs)
                errors[strength].append(sol_dict['error'])
            except Exception as e:
                print(f"error: {strength}")
                print(e)
                continue
    medians = []
    margins = []
    for key, values in errors.items():
        values.sort()
        values = values[1:-1]
        medians.append(median(values))
        margins.append([
            abs(values[0] - median(values)),
            abs(values[-1] - median(values))
        ])
    plt.errorbar(errors.keys(),
                 medians,
                 yerr=np.array(margins).T,
                 fmt='o-',
                 color='blue')
    plt.xlabel('chain strength')
    plt.ylabel('number of error solutions provided (out of 1000)')
    # plt.show()
    plt.savefig('chain_strength.png')
    print(errors)
コード例 #19
0
ファイル: charts.py プロジェクト: ScorpJD/QuantumJSP
def num_of_errors_in_min_gap(qpu=False, start=1.0):
    jobs = {"1": [(0, 2), (1, 1), (2, 1)],
            "2": [(1, 1), (2, 2), (0, 1)],
            "3": [(2, 2), (0, 1), (1, 2)]}

    # best_solution = { "1": [0,2,4],
    #                   "2": [0,2,4],
    #                   "3": [0,2,3]}
    #  result: 5

    import csv
    # wyniki.csv structure:
    # min_classical_gap, not found, incorrect, num_of_reads, 5, 6, 7, 8, 9, more

    with open("wyniki_min_gap.csv", mode='a') as csvfile:
        filewriter = csv.writer(csvfile, delimiter=',',
                                quotechar='|', quoting=csv.QUOTE_MINIMAL)

        # strengths = (25, 30, 35, 40, 45)
        # strengths = list(range(20, 25))
        from numpy import arange
        gaps = list(arange(start, start+.5, 0.1))
        num_reads = 1000
        for gap in gaps:
            for _ in range(10):
                try:
                    bqm = get_jss_bqm(jobs, 8, stitch_kwargs={
                        'min_classical_gap': gap})
                    if qpu:
                        sampler = EmbeddingComposite(
                            DWaveSampler(solver={'qpu': True}))
                        sampleset = sampler.sample(
                            bqm, chain_strength=10.0, num_reads=num_reads)
                    else:
                        sampler = neal.SimulatedAnnealingSampler()
                        sampleset = sampler.sample(bqm, num_reads=num_reads)
                    sol_dict = printResults(sampleset, jobs)
                except Exception as e:
                    print(f"error: {gap}")
                    print(e)
                    from time import sleep
                    sleep(60)
                    continue
                result_row = [gap, sol_dict['error'], sol_dict['incorrect'],
                               num_reads] + [sol_dict[i] for i in range(5, 10)]
                filewriter.writerow(result_row)
                print('zapisane', gap)

        from time import sleep
        sleep(30)
コード例 #20
0
def num_of_errors_in_times(qpu=False):
    jobs = {
        "1": [(0, 2), (1, 1), (0, 1)],
        "2": [(1, 1), (0, 1), (2, 2)],
        "3": [(2, 1), (2, 1), (1, 1)]
    }

    times = range(4, 12)
    errors = defaultdict(list)
    for time in times:
        for i in range(12):
            try:
                bqm = get_jss_bqm(jobs,
                                  time,
                                  stitch_kwargs={'min_classical_gap': 2.0})
                if qpu:
                    sampler = EmbeddingComposite(
                        DWaveSampler(solver={'qpu': True}))
                    sampleset = sampler.sample(bqm,
                                               chain_strength=2,
                                               num_reads=1000)
                else:
                    sampler = neal.SimulatedAnnealingSampler()
                    sampleset = sampler.sample(bqm, num_reads=1000)
                sol_dict = printResults(sampleset, jobs)
                errors[time].append(sol_dict['error'])
            except:
                print(f"error: {time}")
                continue
    medians = []
    margins = []
    for key, values in errors.items():
        values.sort()
        values = values[1:-1]
        medians.append(median(values))
        margins.append([
            abs(values[0] - median(values)),
            abs(values[-1] - median(values))
        ])
    plt.errorbar(errors.keys(),
                 medians,
                 yerr=np.array(margins).T,
                 fmt='o',
                 color='blue')
    plt.xlabel('max_time value')
    plt.ylabel('number of error solutions provided (out of 1000)')
    # plt.show()
    plt.savefig('times.png')
    print(errors)
コード例 #21
0
    def test_chain_break_method_customization(self):
        sampler = EmbeddingComposite(MockDWaveSampler())

        def mock_unembed(*args, **kwargs):
            self.assertIn('chain_break_method', kwargs)
            self.assertEqual(kwargs['chain_break_method'], chain_breaks.discard)
            mock_unembed.call_count += 1
            return dwave.embedding.unembed_sampleset(*args, **kwargs)

        mock_unembed.call_count = 0

        with mock.patch('dwave.system.composites.embedding.unembed_sampleset', mock_unembed):
            sampler.sample_ising({'a': 1}, {}, chain_break_method=chain_breaks.discard).resolve()

        self.assertEqual(mock_unembed.call_count, 1)
コード例 #22
0
def TSP(data, G, weights, s3_folder, machine):

    lagrange_list = get_lagrange_list(G)

    # run TSP with imported TSP routine
    sampler = BraketDWaveSampler(s3_folder, machine)
    sampler = EmbeddingComposite(sampler)

    # set parameters
    num_shots = 1000
    start_city = 0
    best_distance = sum(weights.values())
    best_route = [None] * len(G)

    # run HPO to find route
    for lagrange in lagrange_list:
        print('Running quantum annealing for TSP with Lagrange parameter=',
              lagrange)
        route = traveling_salesperson(G,
                                      sampler,
                                      lagrange=lagrange,
                                      start=start_city,
                                      num_reads=num_shots,
                                      answer_mode="histogram")

        # print distance
        total_dist, distance_with_return = get_distance(route, data)

        # update best values
        if distance_with_return < best_distance:
            best_distance = distance_with_return
            best_route = route

    return best_route, best_distance
コード例 #23
0
ファイル: samplers.py プロジェクト: sajidsaleem/dwave-hybrid
class QPUSubproblemAutoEmbeddingSampler(Runnable, traits.SubproblemSampler):
    """A quantum sampler for a subproblem with automated heuristic minor-embedding.

    Args:
        num_reads (int, optional, default=100):
            Number of states (output solutions) to read from the sampler.
        qpu_sampler (:class:`dimod.Sampler`, optional, default=EmbeddingComposite(DWaveSampler())):
            Quantum sampler such as a D-Wave system. If sampler is structured,
            it will be converted to unstructured via :class:`~dwave.system.composited.EmbeddingComposite`.

    Examples:
        See examples on https://docs.ocean.dwavesys.com/projects/hybrid/en/latest/reference/samplers.html#examples.
    """
    def __init__(self, num_reads=100, qpu_sampler=None):
        super(QPUSubproblemAutoEmbeddingSampler, self).__init__()

        self.num_reads = num_reads

        if qpu_sampler is None:
            qpu_sampler = DWaveSampler()

        # convert the structured sampler to unstructured
        if isinstance(qpu_sampler, dimod.Structured):
            self.sampler = EmbeddingComposite(qpu_sampler)
        else:
            self.sampler = qpu_sampler

    def __repr__(self):
        return ("{self}(num_reads={self.num_reads!r}, "
                "qpu_sampler={self.sampler!r})").format(self=self)

    def next(self, state):
        response = self.sampler.sample(state.subproblem,
                                       num_reads=self.num_reads)
        return state.updated(subsamples=response)
コード例 #24
0
ファイル: Quantum_MNIST.py プロジェクト: mshenron/Leap
def QBoost(X_train, y_train, X_test, y_test):
    NUM_READS = 1000
    DW_PARAMS = {'num_reads': NUM_READS,
                 'auto_scale': True,
                 'num_spin_reversal_transforms': 10,
                 'postprocess': 'optimization',
                 }

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

    dwave_sampler = DWaveSampler(solver={'qpu': True}) 
    emb_sampler = EmbeddingComposite(dwave_sampler)

    from qboost import WeakClassifiers, QBoostClassifier

    clf4 = QBoostClassifier(n_estimators=30, max_depth=2)
    clf4.fit(X_train, y_train, emb_sampler, lmd=1.0, **DW_PARAMS)
    y_train4 = clf4.predict(X_train)
    y_test4 = clf4.predict(X_test)

    from sklearn.metrics import accuracy_score

    print('Accuracy for training data: \t', (accuracy_score(y_train, y_train4)))
    print('Accuracy for test data: \t', (accuracy_score(y_test, y_test4)))
    
    return clf4
コード例 #25
0
    def test_warning_chain_strength(self):
        G = dnx.chimera_graph(12)

        sampler = EmbeddingComposite(
            dimod.StructureComposite(dimod.RandomSampler(), G.nodes, G.edges))

        J = {(0, 1): 100}

        ss = sampler.sample_ising({}, J, warnings='SAVE')
        self.assertIn('warnings', ss.info)

        count = 0
        for warning in ss.info['warnings']:
            if issubclass(warning['type'], ChainStrengthWarning):
                count += 1
        self.assertEqual(count, 1)
コード例 #26
0
def get_solver(solver_type: str, solver_name: str, token):
    filters = {}
    if solver_type.endswith("QPU") and solver_name in QPU_SOLVER_NAME_LIST:
        filters[
            "topology__type"] = "pegasus" if solver_name == "ADVANTAGE" else "chimera"
        filters[
            "name__contains"] = "Advantage_system" if solver_name == "ADVANTAGE" else "DW_2000Q"
    if solver_type.endswith(
            "HYBRID") and solver_name in HYBRID_SOLVER_NAME_LIST:
        filters[
            "name__contains"] = "version2" if solver_name == "HYBRID_V2" else "v1"

    if solver_type == "SA":
        solver = neal.SimulatedAnnealingSampler()
    elif solver_type == "QPU":
        solver = DWaveSampler(client="qpu", solver=filters, token=token)
        solver = EmbeddingComposite(solver)
    elif solver_type == "HYBRID":
        solver = LeapHybridSampler(solver=filters, token=token)
    elif solver_type == "FIXED_QPU":
        solver = DWaveSampler(client="qpu", solver=filters, token=token)
        solver = LazyFixedEmbeddingComposite(solver)
    elif solver_type == "CLIQUE_FIXED_QPU":
        solver = DWaveCliqueSampler(client="qpu", solver=filters, token=token)
    else:
        raise NotImplementedError(
            "Solver {} is not implemented".format(solver_type))
    return solver
コード例 #27
0
def func_solveTSPdwave(
        distanceMatrixLength, token, url, solver,
        qubo):  #Sends the QUBO to the annealer and retrieves the result
    if distanceMatrixLength > 7:  #The numReads variable specifies how many times the annealing will be performed on the QUBO, thus changing the amount of returned samples. The variable is scaled with the amount of countries to be visited, as more countries require more samples to get an accurate result.
        numReads = 4000
    elif distanceMatrixLength > 14:
        numReads = 7000
    else:
        numReads = 2000
    if '2000Q' in solver:  #Sets the chain strength, which scales with the number of countries. In addition, the Advantage system provides better results with a lower chain strength than the 2000Q system.
        chain = distanceMatrixLength * 100
    else:
        chain = int(round((distanceMatrixLength * 100) / 1.5, 0))
    timeStart = time.time(
    )  #Makes a timestamp of when the annealing process began
    try:
        binaryResult = EmbeddingComposite(
            DWaveSampler(
                token=token, endpoint=url, solver=solver)).sample_qubo(
                    qubo, chain_strength=chain,
                    num_reads=numReads)  #Sends the QUBO to the annealer
    except Exception as error:  #Attempts to catch an exception if one is returned by the D-Wave system
        print(
            f'An error has occured while trying to send the problem to the annealer: {error}'
        )
        print('The calculation has been cancelled, returning to main menu.')
        return None, None, True
    print(
        f'\nBinarized optimal solution returned by the annealer:\n{binaryResult}'
    ) if debug == True else ''
    return binaryResult, timeStart, None
コード例 #28
0
    def __init__(self, num_reads=100, qpu_sampler=None):
        super(QPUSubproblemAutoEmbeddingSampler, self).__init__()

        self.num_reads = num_reads
        if qpu_sampler is None:
            qpu_sampler = EmbeddingComposite(DWaveSampler())
        self.sampler = qpu_sampler
コード例 #29
0
    def test_warnings_as_class_variable(self):
        G = dnx.chimera_graph(12)

        sampler = EmbeddingComposite(
            dimod.StructureComposite(dimod.RandomSampler(), G.nodes, G.edges))

        # this will need chains lengths > 7
        J = {uv: -1 for uv in itertools.combinations(range(40), 2)}

        EmbeddingComposite.warnings_default = 'SAVE'

        ss = sampler.sample_ising({}, J)

        self.assertIn('warnings', ss.info)

        EmbeddingComposite.warnings_default = 'IGNORE'  # restore default
コード例 #30
0
ファイル: perf.py プロジェクト: kslaughter/dwave-hybrid
def run(problems, solver_factories):
    results = OrderedDict()

    # reuse the cloud client
    qpu = EmbeddingComposite(DWaveSampler())

    for problem in problems:
        results[problem] = OrderedDict()

        with open(problem) as fp:
            bqm = dimod.BinaryQuadraticModel.from_coo(fp)

        for name, factory in solver_factories:
            case = '{!r} with {!r}'.format(problem, name)

            try:
                solver = factory(qpu=qpu)
                init_state = State.from_sample(min_sample(bqm), bqm)

                with tictoc(case) as timer:
                    solution = solver.run(init_state).result()

            except Exception as exc:
                print("FAILED {case}: {exc!r}".format(**locals()))
                results[problem][name] = repr(exc)

            else:
                print("case={case!r}"
                      " energy={solution.samples.first.energy!r},"
                      " wallclock={timer.dt!r}".format(**locals()))
                results[problem][name] = dict(
                    energy=solution.samples.first.energy, wallclock=timer.dt)