Esempio n. 1
0
def test_quantum2():
    ''' Example using D-Wave's quantum annealing
    
    Note: Embedding is done with the use of D-Wave composite
    '''
    X = np.array([[1, 2], [1, 3], [9, 5], [9, 6]])  # input data
    k = 2
    model = genModel(X, k)  # generate BQM model (not yet embedded)
    sampler = EmbeddingComposite(DWaveSampler(
        solver={'qpu': True
                }))  # sets D-Wave's sampler, embedding is done automatically
    solution_set = sampler.sample(
        model, num_reads=100,
        return_embedding=True)  # run on the D-wave hardware
    print("Embedding: ", solution_set.info["embedding_context"]["embedding"])
    # Count the number of qubits used
    num_qubits = 0
    for entry in solution_set.info["embedding_context"]["embedding"].values():
        num_qubits += len(entry)
    print("Number of qubits: ", num_qubits)
    M, assignments = postprocess2(
        X, solution_set.first.sample)  # postprocess the solution
    print("Centroids: ")
    print(M)
    print("Assignments: " + str(assignments))
Esempio n. 2
0
def objective(trial):
    b1 = trial.suggest_uniform('b1', 0.0, 20)
    b2 = trial.suggest_uniform('b2', 0.0, 20)
    b3 = trial.suggest_uniform('b3', 0.0, 20)

    def_dict = {
        "balancer1": b1,
        "balancer2": b2,
        "balancer3": b3,
        "IntChain": 1.0
    }
    bqm = model.to_dimod_bqm(feed_dict=def_dict)

    sampler = EmbeddingComposite(DWaveSampler(sampler="DW_2000Q_6"))
    responses = sampler.sample(bqm, num_reads=5000)

    solutions = model.decode_dimod_response(responses, feed_dict=def_dict)

    cnt = 0

    for idx, sol in enumerate(solutions):
        if len(sol[1]) < 10:
            cnt += responses.record[idx][2]

    return cnt
Esempio n. 3
0
    def test_many_bqm_async(self):
        sampler = EmbeddingComposite(self.qpu)

        # in the future it would be good to test a wide variety of BQMs,
        # see https://github.com/dwavesystems/dimod/issues/671
        # but for now let's just test a few
        bqm0 = dimod.BinaryQuadraticModel.from_ising({
            'a': 2.0,
            'b': -2.0
        }, {('a', 'b'): -1})
        bqm1 = dimod.BinaryQuadraticModel.from_ising({2: 4}, {
            (0, 1): 1.5,
            (1, 2): 5
        })

        samplesets0 = []
        samplesets1 = []
        for _ in range(10):
            # this should be async
            samplesets0.append(sampler.sample(bqm0))
            samplesets1.append(sampler.sample(bqm1))

        if all(ss.done() for ss in samplesets0):
            warnings.warn("Sampler calls appear to be synchronous")

        for ss0, ss1 in zip(samplesets0, samplesets1):
            dimod.testing.assert_sampleset_energies(ss0, bqm0)
            dimod.testing.assert_sampleset_energies(ss1, bqm1)

        self.assertTrue(all(ss.done() for ss in samplesets0))
        self.assertTrue(all(ss.done() for ss in samplesets1))
Esempio n. 4
0
def cluster_points(scattered_points, filename):
    # Set up problem
    # Note: max_distance gets used in division later on. Hence, the max(.., 1)
    #   is used to prevent a division by zero
    coordinates = [Coordinate(x, y) for x, y in scattered_points]
    max_distance = max(get_max_distance(coordinates), 1)

    # Build constraints
    csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

    # Apply constraint: coordinate can only be in one colour group
    choose_one_group = {(0, 0, 1), (0, 1, 0), (1, 0, 0)}
    for coord in coordinates:
        csp.add_constraint(choose_one_group, (coord.r, coord.g, coord.b))

    # Build initial BQM
    bqm = dwavebinarycsp.stitch(csp)

    # Edit BQM to bias for close together points to share the same color
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            d = get_distance(coord0, coord1) / max_distance  # rescale distance
            weight = -math.cos(d * math.pi)

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.b, weight)

    # Edit BQM to bias for far away points to have different colors
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            # Note: rescaled and applied square root so that far off distances
            #   are all weighted approximately the same
            d = math.sqrt(get_distance(coord0, coord1) / max_distance)
            weight = -math.tanh(d) * 0.1

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.b, weight)
            bqm.add_interaction(coord0.r, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.r, weight)
            bqm.add_interaction(coord0.b, coord1.g, weight)
            bqm.add_interaction(coord0.g, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.b, weight)

# Submit problem to D-Wave sampler
    sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
    #sampler = neal.SimulatedAnnealingSampler()
    sampleset = sampler.sample(bqm, chain_strength=4, num_reads=1000)
    best_sample = sampleset.first.sample

    # Visualize graph problem
    dwave.inspector.show(bqm, sampleset)

    # Visualize solution
    groupings = get_groupings(best_sample)
    visualize_groupings(groupings, filename)
    return groupings
Esempio n. 5
0
    def solve_QPU(
        self,
        h1=1.0,
        num=100,
        sol="DW_2000Q_6",
        emb_param={
            "verbose": 2,
            "max_no_improvement": 6000,
            "timeout": 600,
            "chainlength_patience": 1000,
            "threads": 15
        }):
        '''
            EmbeddingComposite サンプラを用いた、Solver。結果を変数に格納する
            self.best_dist 得られた最良の距離(最短距離)
            self.best_route 得られた最良のルート
        

        parameters
        -----
            float h1(default 1.0) : ModelからQUBO行列を作成する際の距離の重み
            float h1(default 1.0) : ModelからQUBO行列を作成する際の制約の重み
            int num : サンプリング回数
            str sol : Solver名
            dict emb_param : 内部で呼ばれるfind_embeddingのオプション

        returns
        -----
            なし
        '''

        sampler = EmbeddingComposite(DWaveSampler(solver=sol))
        #QUBO変換
        Q, offset = self.model.to_qubo(feed_dict={"H1": h1})
        #D-Waveへデータ送信
        self.responses = sampler.sample_qubo(Q,
                                             num_reads=num,
                                             chain_strength=5.0,
                                             embedding_parameters=emb_param,
                                             postprocess="optimization")
        #結果をDecode(Constraintをチェックするため)
        self.solutions = self.model.decode_dimod_response(self.responses,
                                                          feed_dict={"H1": h1})

        #ベストな距離を変数に格納する
        self.best_dist = 100000
        self.best_route = []

        for sol in self.solutions:
            #制約違反がない結果について、過去のBestの距離と比較
            if len(sol[1]) == 0:
                tmp_sol = [
                    sum(i * val for i, val in sol[0]['x'][j].items())
                    for j in range(self.size)
                ]
                if self.route_len(tmp_sol) < self.best_dist:
                    self.best_dist = self.route_len(tmp_sol)
                    self.best_route = tmp_sol
Esempio n. 6
0
    def test_dwave_system(self):
        from dwave.system import DWaveSampler, EmbeddingComposite

        sampler = EmbeddingComposite(DWaveSampler())

        h = {'a': -1, 'b': +1}
        J = {('a', 'b'): -1}

        resp = sampler.sample_ising(h, J)
Esempio n. 7
0
def main(token='', n_vertices=0, neighbours=None, filename=None, local=False):
    ''' Using any graph at all, if given the number of nodes
    and the neighbours, 0-indexed, this will try to minimize the
    number of same-coloured neighbours.

    Runs on the Basic Dwave Solver, so very quickly and painlessly.

    :param n_vertices: This is the number of vertices in the graph to be 2-coloured.
        Vertices should be 0-indexed.

    :param neighbours: This is the adjacency list describing the graph.
        This should only describe vertex indices, 0-indexed.
    
    :param filename: If the problem is desired to be loaded from a file,
        this string should be the path to that file.
    
    :param local: Utilized solely by __main__, will make the program output
        the whole solution for display in Dwave's web inspector.

    :param token: The Dwave token to be used.
        This should be a string, in the format used on the dwave leap website.

    :return: This returns a dictionary. The only key is "solution",
        containing an ordered list of the states of the vertices for the best solution.
        Each state is either 1 or -1.

    '''
    if filename == None:
        filename = 'problem.txt'

    if neighbours == None:
        n_vertices, neighbours = load_problem(filename)

    # 2. Define problem

    h = [0 for x in range(n_vertices)]
    J = dict((tuple(neighbour), 10) for neighbour in neighbours)
    # print(J)

    # 3. Instantiate solver
    sampler = EmbeddingComposite(DWaveSampler(token=token))

    # 4. Sample problem

    solution = sampler.sample_ising(h, J, chain_strength=50, num_reads=50)

    # 5. Use response

    best_solution = [int(solution.first.sample[x]) for x in range(n_vertices)]

    # print( best_solution )
    if local:
        return solution
    else:
        return {'solution': best_solution}
    def test_initial_state(self):
        sampler = EmbeddingComposite(self.qpu)

        bqm = dimod.BinaryQuadraticModel.from_ising({'a': 2.0, 'b': -2.0},
                                                    {('a', 'b'): -1})

        kwargs = {'initial_state': {'a': 1, 'b': 1},
                  'anneal_schedule': [(0, 1), (55.0, 0.45),
                                      (155.0, 0.45), (210.0, 1)]}

        sampler.sample(bqm, **kwargs).resolve()
Esempio n. 9
0
    def solve(self):

        if (self.useQPU):
            sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
            sampleset = sampler.sample_qubo(self.Q,
                                            num_reads=self.n_reads,
                                            chain_strength=self.chain)
        elif (self.useNeal):
            bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset)
            sampler = neal.SimulatedAnnealingSampler()
            sampleset = sampler.sample(bqm,
                                       num_reads=self.n_reads,
                                       chain_strength=self.chain)
        elif (self.useHyb):
            bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset)
            sampler = LeapHybridSampler()
            sampleset = sampler.sample(bqm, num_reads=self.n_reads)
        else:
            bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset)
            sampler = TabuSampler()
            sampleset = sampler.sample(bqm,
                                       num_reads=self.n_reads,
                                       chain_strength=self.chain)

        self.sampleset = sampleset
Esempio n. 10
0
def factor(P):
    bP = "{:06b}".format(P)
    csp = dbc.factories.multiplication_circuit(3)
    bqm = dbc.stitch(csp, min_classical_gap=.1)
    p_vars = ['p0', 'p1', 'p2', 'p3', 'p4', 'p5']
    fixed_variables = dict(zip(reversed(p_vars), bP))
    fixed_variables = {var: int(x) for (var, x) in fixed_variables.items()}
    for var, value in fixed_variables.items():
        bqm.fix_variable(var, value)

    sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
    sampleset = sampler.sample(bqm, num_reads=1000)
    a, b = to_base_ten(sampleset.first.sample)
    print("Given integer P={0}, found factors a={1} and b={2}".format(P, a, b))
    return a, b
Esempio n. 11
0
    def optimize_advantage(self,count=False,Best=0,balancer=1.0):
        from pyqubo import Array,Constraint,Placeholder,UnaryEncInteger,Sum #LogEncInteger
        from dwave.system import EmbeddingComposite,DWaveSampler

        x = Array.create("x",shape=(self.num),vartype="BINARY")
        #y = LogEncInteger("y",lower=0,upper=5)
        y = UnaryEncInteger("y",lower=0,upper=5)

        #価値が最大になるように(符号を反転させる)
        #H1 = -sum([x[i]*self.p[i].get_value() for i in range(self.num)])
        H1 = -Sum(0,self.num,lambda i :x[i]*self.p[i].get_value() )

        #重さが目的の重量になるように
        #H2 = Constraint((self.limit_weight -sum([x[i]*p_i.get_weight() for i,p_i in enumerate(self.p)]) - y*10)**2,"Const Weight")
        H2 = Constraint((self.limit_weight -Sum(0,self.num,lambda i: x[i]*self.p[i].get_weight()) - y*10)**2,"Const Weight")
        #H2 = Constraint((self.limit_weight -Sum(0,self.num,lambda i: x[i]*self.p[i].get_weight()))**2,"Const Weight")

        H = H1 + H2*Placeholder("balancer")
        model = H.compile()
        balance_dict = {"balancer":balancer}
        bqm = model.to_dimod_bqm(feed_dict=balance_dict)
        sampler = EmbeddingComposite(DWaveSampler(solver="Advantage_system1.1"))
        #sampler = EmbeddingComposite(DWaveSampler(solver="DW_2000Q_6"))
        responses = sampler.sample(bqm,num_reads=1000)

        solutions = model.decode_dimod_response(responses,feed_dict=balance_dict)
        #Optuna用 バランス調査
        if count == True:
            counter = 0
            for idx,sol in enumerate(solutions):
                const_str = sol[1]
                val = sum(int(sol[0]['x'][i])*self.p[i].get_value()  for i in range(self.num))
                weight = sum(int(sol[0]['x'][i])*self.p[i].get_weight()  for i in range(self.num))
                #重量が制限以下、かつ価値が最適解の9割以上をカウント
                if len(const_str) == 0 and val > Best*0.9 and weight <= self.limit_weight:
                    counter += responses.record[idx][2]

            del H1,H2,H,model,bqm,responses,solutions
            gc.collect()

            return counter

        if len(solutions[0][1]) == 0:
            print(f" y= { sum(2**i*y_i for i,y_i in enumerate(solutions[0][0]['y']))}")
            print("## Advantage Solver Optimized Result")
            self.print([int(solutions[0][0]['x'][i]) for i in range(self.num)])
        else:
            print("## Advantage Solver Optimizing Failed")
Esempio n. 12
0
def solve_dwave(Q, conf_file, **kwargs):
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    from dwave.system import EmbeddingComposite
    from dwave.system import DWaveSampler
    sampler = DWaveSampler(config_file=conf_file, permissive_ssl=True)
    solver = EmbeddingComposite(sampler)
    logger.info(f'Using {sampler.solver} as the sub-QUBO solver.')
    return solve_qbsolv(Q, solver=solver, **kwargs)
Esempio n. 13
0
def set_sampler():
    '''Returns a dimod sampler'''

    token = get_token()
    sampler = EmbeddingComposite(
        DWaveSampler(endpoint='https://cloud.dwavesys.com/sapi/',
                     token=token,
                     solver={'qpu': True}))

    return sampler
Esempio n. 14
0
 def __init__(self, qmasm, profile=None, solver=None, qbsolv=False):
     "Acquire either a software sampler or a sampler representing a hardware solver."
     self.qmasm = qmasm
     self.sampler, self.client_info = self._get_sampler(profile, solver)
     if qbsolv:
         if solver == None:
             self.qbsolv_sampler = EmbeddingComposite(self.sampler)
         else:
             self.qbsolv_sampler = self.sampler
         self.sampler = QBSolv()
         self.client_info[
             "solver_name"] = "QBSolv + " + self.client_info["solver_name"]
     else:
         self.qbsolv_sampler = None
def main(sampler_type, region, show, inspect):

    if sampler_type is None:
        print("No solver selected, defaulting to hybrid")
        sampler_type = 'hybrid'

    # get the appropriate signed social network
    G = global_signed_social_network(region=region)

    # choose solver and any tuning parameters needed
    if sampler_type == 'cpu':
        params = dict(num_reads=100)
        sampler = SimulatedAnnealingSampler()

    elif sampler_type == 'hybrid':
        params = dict()
        sampler = LeapHybridSampler()

    elif sampler_type == 'qpu':
        params = dict(
            num_reads=100,
            chain_strength=2.0,
        )
        sampler = dimod.TrackingComposite(EmbeddingComposite(DWaveSampler()))

    else:
        raise RuntimeError("unknown solver type")

    # use the chosen sampler (passing in the parameters)
    edges, colors = dnx.structural_imbalance(
        G, sampler, label='Example - Structural Imbalance', **params)

    if inspect and sampler_type == 'qpu':
        dwave.inspector.show(sampler.output)

    print("Found", len(edges), 'violations out of', len(G.edges), 'edges')

    draw_social_network(G, colors)

    if show:
        plt.show()
    else:
        filename = 'structural imbalance {} {}.png'.format(
            sampler_type, region)
        plt.savefig(filename, facecolor='white')
        plt.clf()
Esempio n. 16
0
def main(sampler_type, region, show):

    if sampler_type is None:
        print("No solver selected, defaulting to hybrid")
        sampler_type = 'hybrid'

    if region == 'global' and sampler_type == 'qpu':
        print("Given region is too large for the QPU, please choose another "
              "region or use hybrid.")

    # get the appropriate signed social network
    G = global_signed_social_network(region=region)

    # choose solver and any tuning parameters needed
    if sampler_type == 'cpu':
        params = dict(num_reads=100)
        sampler = SimulatedAnnealingSampler()

    elif sampler_type == 'hybrid':
        params = dict()
        sampler = LeapHybridSampler()

    elif sampler_type == 'qpu':
        params = dict(
            num_reads=100,
            chain_strength=2.0,
        )
        sampler = EmbeddingComposite(DWaveSampler())

    else:
        raise RuntimeError("unknown solver type")

    # use the chosen sampler (passing in the parameters)
    edges, colors = dnx.structural_imbalance(G, sampler, **params)

    print("Found", len(edges), 'violations out of', len(G.edges), 'edges')

    draw_social_network(G, colors)

    if show:
        plt.show()
    else:
        filename = 'stuctural imbalance {} {}.png'.format(sampler_type, region)
        plt.savefig(filename, facecolor='white', dpi=500)
        plt.clf()
Esempio n. 17
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)
Esempio n. 18
0
    def solve(self, 
              useQPU=False, 
              useNeal=False, 
              useHyb=True,
              time_limit = 10,
              num_reads = 100,
              chain_strength = 10000):
        
        Q = self.Q
        BQM_offset = 0 # TODO: Use the accumulated quadratic constants from the constraints

        bqm = BinaryQuadraticModel.from_qubo(Q, offset=BQM_offset)

        self.sampleset = None
        
        # Call the requested solver
        
        if ( useQPU ):
            print("Solving using the DWaveSampler on the QPU...")
            sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
            sampleset = sampler.sample_qubo(Q, num_reads=num_reads,chain_strength = chain_strength)
        elif ( useHyb ): 
            print("Solving using the LeapHybridSolver...")
            sampler = LeapHybridSampler()
            sampleset = sampler.sample(bqm, time_limit = time_limit)
        elif ( useNeal ): 
            print("Solving using the SimulatedAnnealing...")
            sampler = neal.SimulatedAnnealingSampler()
            sampleset = sampler.sample(bqm, num_reads = num_reads)
        else:
            print("Solving using the TabuSampler...")
            sampler = TabuSampler()
            sampleset = sampler.sample(bqm, num_reads = num_reads)

        self.sampleset = sampleset
        
        count = 0
        for res in self.sampleset.data(): count += 1
        
        return (count)
Esempio n. 19
0
File: maxcut.py Progetto: 84monta/OR
    def solve_dwave(self):
        X = Array.create('X', shape=(self.n), vartype='SPIN')

        H0 = 0
        for (u, v) in self.G.edges:
            H0 -= (1 - X[u] * X[v]) * self.G.edges[u, v]['w']

        model = H0.compile()
        bqm = model.to_dimod_bqm()

        response = EmbeddingComposite(DWaveSampler()).sample(bqm,
                                                             num_reads=100)

        result = model.decode_dimod_response(response, topk=1)
        optimized_v = result[0][0]['X']

        self.v_group = []
        for i in range(self.n):
            self.v_group.append(optimized_v[i])

        self.cutted = []
        for (u, v) in self.G.edges:
            if optimized_v[u] != optimized_v[v]:
                self.cutted.append([u, v])
Esempio n. 20
0
from dijkstra_solver import dijkstra_solver
import networkx as nx
from dimod import BinaryQuadraticModel
import dimod
import dwave.inspector
from dwave.system import DWaveSampler, EmbeddingComposite

G = nx.Graph()
G.add_weighted_edges_from([('S', 'a', 4.0), ('a', 'b', 7.0), ('b', 'G', 2.0),
                           ('G', 'd', 3.0), ('c', 'd', 8.0), ('c', 'S', 6.0),
                           ('c', 'b', 9.0)])
lagrange = 20
chainstrength = 20
numruns = 1000

model = dijkstra_solver(G, 'S', 'G', lagrange)
Q = model.to_qubo()
bqm = BinaryQuadraticModel.from_qubo(Q[0], offset=Q[1])
sampler = EmbeddingComposite(DWaveSampler())
sampleset = sampler.sample(bqm,
                           chain_strength=chainstrength,
                           num_reads=numruns)
dwave.inspector.show(bqm, sampleset, sampler)
Esempio n. 21
0
    # Constrain I: there should be N segments in the trip
    Q_cI = defaultdict(int)
    for i in range(N_tot):
        Q_cI[(i, i)] = l_I * (1 - 2 * N_req)
        for j in range(i+1, N_tot):
            Q_cI[(i, j)] = l_I * 2

    # Constrain II: the trip should start and finish at the North Pole
    Q_cII = defaultdict(int)
    for i in range(N_tot):
        Q_cII[(i, i)] = l_II
    Q_cII[(0, 2)] = -l_II * 2
    Q_cII[(1, 3)] = -l_II * 2
    Q_cII[(4, 5)] = -l_II * 2

    QUBO_print("Q_goal", Q_goal, N_tot)
    QUBO_print("Q_cI", Q_cI, N_tot)
    QUBO_print("Q_cII", Q_cII, N_tot)

    Q = QUBO_sum(Q_cI, Q_cII);
    Q = QUBO_sum(Q, Q_goal);

    chain_strength = QUBO_guess_chain_strength(Q)

    print("Chain Strength: {}".format(chain_strength), end="\n\n")

    sampleset = EmbeddingComposite(DWaveSampler()).sample_qubo(
        Q, num_reads=10, chain_strength=chain_strength)
    print(sampleset)
csp = full_adder(csp, "a1", "b1", "cin", "0")
csp = full_adder(csp, "a2", "b2", "0_cout", "1")
csp = full_adder(csp, "a3", "b3", "1_cout", "2")
csp = full_adder(csp, "a4", "b4", "2_cout", "3")
csp = full_adder(csp, "a5", "b5", "3_cout", "4")
csp = full_adder(csp, "a6", "b6", "4_cout", "5")
csp = full_adder(csp, "a7", "b7", "5_cout", "6")
csp = full_adder(csp, "a8", "b8", "6_cout", "7")
csp = full_adder(csp, "a9", "b9", "7_cout", "8")
csp = full_adder(csp, "a10", "b10", "8_cout", "9")

for i in range(0, 9):
    csp.fix_variable("sum" + str(i), 1)

csp.fix_variable("9_cout", 1)

bqm = dbc.stitch(csp)

sampler = EmbeddingComposite(DWaveSampler(solver={"qpu": True}))
sampleset = sampler.sample(bqm, num_reads=10000)
print(sampleset)

for sample, energy in sampleset.data(["sample", "energy"]):
    string = ""
    for i in range(1, 10):
        string += "a" + str(i) + ": " + str(sample["a" + str(i)]) + ", "
        string += "b" + str(i) + ": " + str(sample["b" + str(i)]) + ", "
    string += "cin: " + str(sample["cin"]) + " energy: " + str(energy)
    print(string)

dwave.inspector.show(sampleset)
def cluster_points(scattered_points, filename, architecture):
    # Set up problem
    # Note: max_distance gets used in division later on. Hence, the max(.., 1)
    #   is used to prevent a division by zero
    coordinates = [Coordinate(x, y) for x, y in scattered_points]
    max_distance = max(get_max_distance(coordinates), 1)

    # Build constraints
    csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

    # Apply constraint: coordinate can only be in one colour group
    choose_one_group = {(0, 0, 1), (0, 1, 0), (1, 0, 0)}
    for coord in coordinates:
        csp.add_constraint(choose_one_group, (coord.r, coord.g, coord.b))

    # Build initial BQM
    bqm = dwavebinarycsp.stitch(csp)

    # Edit BQM to bias for close together points to share the same color
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            d = get_distance(coord0, coord1) / max_distance  # rescale distance
            weight = -math.cos(d * math.pi)

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.b, weight)

    # Edit BQM to bias for far away points to have different colors
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            # Note: rescaled and applied square root so that far off distances
            #   are all weighted approximately the same
            d = math.sqrt(get_distance(coord0, coord1) / max_distance)
            weight = -math.tanh(d) * 0.1

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.b, weight)
            bqm.add_interaction(coord0.r, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.r, weight)
            bqm.add_interaction(coord0.b, coord1.g, weight)
            bqm.add_interaction(coord0.g, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.b, weight)

    # Submit problem to D-Wave sampler
    if architecture == 'pegasus':
        solver = DWaveSampler(solver={
            'topology__type': 'pegasus',
            'qpu': True
        })
        print(solver.solver)

        sampler = EmbeddingComposite(solver)
    else:
        solver = DWaveSampler(solver={
            'topology__type': 'chimera',
            'qpu': True
        })
        print(solver.solver)

        sampler = EmbeddingComposite(solver)

    sampleset = sampler.sample(bqm,
                               chain_strength=4,
                               num_reads=1000,
                               return_embedding=True)
    best_sample = sampleset.first.sample

    # Inspect the embedding
    embedding = sampleset.info['embedding_context']['embedding']
    num_qubits = 0

    for k in embedding.values():
        num_qubits += len(k)
    print("Number of qubits used in embedding = " + str(num_qubits))

    # Visualize graph problem
    dwave.inspector.show(bqm, sampleset)

    # Visualize solution
    groupings = get_groupings(best_sample)
    visualize_groupings(groupings, filename)

    # Print solution onto terminal
    # Note: This is simply a more compact version of 'best_sample'
    print(groupings)
from collections import defaultdict
import networkx as nx

# 2. Set up the problem
# Create empty graph
G = nx.Graph()

# Add edges to the graph (also adds nodes)
G.add_edges_from([('a', 'b'), ('b', 'c'), ('b', 'd'), ('c', 'd'), ('c', 'f'),
                  ('d', 'f'), ('d', 'e'), ('e', 'f')])
print(G.edges)

# ------- Set up our QUBO dictionary -------
# Initialize our Q matrix
Q = defaultdict(int)

# Update Q matrix for every edge in the graph
for i, j in G.edges:
    Q[(i, i)] += -1
    Q[(j, j)] += -1
    Q[(i, j)] += 2

# 3. Instantiate a solver
sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))

# 4. Solve the problem
sampleset = sampler.sample_qubo(Q, chain_strength=8, num_reads=100)

# 5. Interpret the results - print the results with the lowest energy
print(sampleset.lowest())
Esempio n. 25
0
def generateRealSamples(qubo, num_reads=10):

    sampler = DWaveSampler()
    embedding = EmbeddingComposite(sampler)
    return embedding.sample_qubo(qubo, num_reads=guarded_num_reads(num_reads))
Esempio n. 26
0
from cliparser import parser

if __name__ == "__main__":
    args = parser.parse_args()
    options = {
        'no_time': args.no_time,
        'verbosity': args.verbosity
    }

    if args.solver in ['hybrid', 'embed', 'sim_anneal', 'tabu']:
        solverClass = DwaveSolver

        if args.solver == 'hybrid':
            options['solver'] = LeapHybridSampler()
        elif args.solver == 'embed':
            options['solver'] = EmbeddingComposite(DWaveSampler())
        elif args.solver == 'sim_anneal':
            options['solver'] = neal.SimulatedAnnealingSampler()
        elif args.solver == 'tabu':
            options['solver'] = 'tabu'

        options['visualize'] = args.visualize
        options['top_samples'] = args.sols_to_print

    elif args.solver == 'cplex':
        solverClass = CplexNeosSolver
    elif args.solver == 'qiskit':
        solverClass = QiskitSolver

    solver = solverClass(args.num_molecules, args.lattice_size)
    solver.solve(options)
Esempio n. 27
0
    numruns = 1  # update

    sample_set = sampler.sample_qubo(Q,
                                     chain_strength=chainstrength,
                                     num_reads=numruns)

    return sample_set


## ------- Main program -------
if __name__ == "__main__":

    token = get_token()

    ## ------- Set up our QUBO dictionary -------

    Q = get_qubo()

    ## ------- Run our QUBO on the QPU -------

    sampler = EmbeddingComposite(
        DWaveSampler(endpoint='https://cloud.dwavesys.com/sapi/',
                     token=token,
                     solver={'qpu': True}))

    sample_set = run_on_qpu(Q, sampler)

    ## ------- Return results to user -------
    for sample, energy in sample_set.data(['sample', 'energy']):
        print(sample, energy)
Esempio n. 28
0
def cluster_points(scattered_points, filename):
    # Set up problem
    coordinates = [Coordinate(x, y) for x, y in scattered_points]
    max_distance = get_max_distance(coordinates)

    # Build constraints
    csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

    # Apply constraint: coordinate can only be in one colour group
    choose_one_group = allowed_States(k)
    for coord in coordinates:
        mylist = list(vars(coord).values())
        mylist.remove(coord.x)
        mylist.remove(coord.y)

        csp.add_constraint(choose_one_group, mylist)

    # Build initial BQM
    bqm = dwavebinarycsp.stitch(csp)

    # Edit BQM to bias for close together points to share the same color
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            d = get_distance(coord0, coord1) / max_distance  # rescale distance
            weight = -math.cos(d * math.pi)

            # Apply weights to BQM

            for i in range(k):
                bqm.add_interaction(getattr(coord0, "x" + str(i)),
                                    getattr(coord1, "x" + str(i)), weight)

    # Edit BQM to bias for far away points to have different colors
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            # Note: rescaled and applied square root so that far off distances
            #   are all weighted approximately the same
            d = math.sqrt(get_distance(coord0, coord1) / max_distance)
            weight = -math.tanh(d) * 0.1

            # Apply weights to BQM
            for p in range(k):
                for m in range(k):
                    if p != m:
                        bqm.add_interaction(getattr(coord0, "x" + str(p)),
                                            getattr(coord1, "x" + str(m)),
                                            weight)

    # Submit problem to D-Wave sampler
    sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
    sampleset = sampler.sample(bqm, chain_strength=4, num_reads=1000)
    best_sample = sampleset.first.sample

    # Visualize graph problem
    dwave.inspector.show(bqm, sampleset)

    # Visualize solution
    groupings = get_groupings(best_sample)
    visualize_groupings(groupings, filename)

    # Print solution onto terminal
    # Note: This is simply a more compact version of 'best_sample'
    print(groupings)
Esempio n. 29
0
from dwave.system import DWaveSampler, EmbeddingComposite
import dwave.inspector

sampler = EmbeddingComposite(DWaveSampler(solver='DW_2000Q_6',
                                          #token='',
                                          ))

h = {}

J = {
    ('Lisa', 'Timo'): 3,
    # Ergänzen Sie hier die Werte
    # der anderen Koppler
}

response = sampler.sample_ising(
    h,
    J,
    num_reads=100,
    chain_strength=1,  # hiermit müssen Sie
    # rumspielen um
    # gute Lösungen zu
    # bekommen
    annealing_time=20,  # diesen Wert
    # können Sie zstl.
    # ändern um bessere
    # Lösungen zu
    # bekommen
)
dwave.inspector.show(response)
Esempio n. 30
0
from dwave.system import DWaveSampler, EmbeddingComposite
import random
import pyqubo

sampler = EmbeddingComposite(DWaveSampler())

N = int(input())
m = int(input())

weight = [random.randint(-100, 100) for i in range(N)]
x = pyqubo.Array.create('bin_array', shape=N, vartype='BINARY')

lagrangian = 0
for elem in weight:
    lagrangian += abs(elem)

hamiltonian = -sum(
    a * j for a, j in zip(weight, x)) + lagrangian * (sum(i for i in x) - m)**2

Q, offset = hamiltonian.compile().to_qubo()
sampleset = sampler.sample_qubo(Q, num_reads=1000)
print(sampleset)  # doctest: +SKIP
print(' '.join(map(str, weight)))