Пример #1
0
    def solve(self, verbose=False, num_repeats=50, target=None, debug=False):
        if self.qubo is None:
            self.pre_process()
        if verbose:
            print("Solving MAX-SMTI with Qbsolv")
        if self.qubo_size == 0 or self.qubo_size == 1:
            if debug:
                return None
            return Solution(self.matching, self.pre_evaluated_solution)

        if self.mode == "np":  # more memory intensive
            response = QBSolv().sample(BinaryQuadraticModel.from_numpy_matrix(self.qubo), num_repeats=num_repeats,
                                       target=target)
        elif self.mode == "bqm":
            response = QBSolv().sample(self.qubo, num_repeats=num_repeats, target=target)
        else:
            raise Exception(f"mode: {self.mode} cannot be solved yet")
        if debug:
            return response
        if verbose:
            print(response)
            for index, sample in enumerate(list(response.samples())):
                match, valid = self.encode(sample)
                print(index, ":", Solution(self.matching, match).is_stable(), match, valid)
        energies = list(response.data_vectors['energy'])
        min_en = min(energies)
        ret_match, valid = self.encode(list(response.samples())[energies.index(min_en)])
        return Solution(self.matching, ret_match, energy=min_en)
Пример #2
0
    def solve_multi_data(self, verbose=False, target=None, num_repeats=200):
        if self.qubo is None:
            self.pre_process()
        if verbose:
            print("Solving multiple solutions of MAX-SMTI with Qbsolv")
        if self.qubo_size == 0 or self.qubo_size == 1:
            return [Solution(self.matching, self.pre_evaluated_solution)]

        if self.mode == "np":  # more memory intensive
            response = QBSolv().sample(BinaryQuadraticModel.from_numpy_matrix(self.qubo), num_repeats=num_repeats,
                                       target=target, algorithm=SOLUTION_DIVERSITY)
        elif self.mode == "bqm":
            response = QBSolv().sample(self.qubo, num_repeats=num_repeats, target=target)
        else:
            raise Exception(f"mode: {self.mode} cannot be solved yet")

        if verbose:
            print(response)
            for index, sample in enumerate(list(response.samples())):
                match, valid = self.encode(sample)
                print(index, ":", Solution(self.matching, match).is_stable(), match, valid)

        samples = pd.DataFrame()
        for sample, energy, occ in response.record:
            match, valid = self.encode_qa(sample.tolist())
            stable, size = Solution(self.matching, match).is_stable()
            samples = samples.append({"match": match, "sample": sample.tolist(),
                                      "energy": energy, "occ": occ,
                                      "valid": valid, "stable": stable, "size": size}, ignore_index=True)
        return samples
Пример #3
0
    def solve_multi(self, verbose=False, num_repeats=200):
        if self.qubo is None:
            self.pre_process()

        if verbose:
            print("Solving multiple solutions of MAX-SMTI with Qbsolv")
        if self.qubo_size == 0 or self.qubo_size == 1:
            return [Solution(self.matching, self.pre_evaluated_solution)]

        if self.mode == "np":  # more memory intensive
            response = QBSolv().sample(BinaryQuadraticModel.from_numpy_matrix(self.qubo), num_repeats=num_repeats)
        elif self.mode == "bqm":
            response = QBSolv().sample(self.qubo, num_repeats=num_repeats)
        else:
            raise Exception(f"mode: {self.mode} cannot be solved yet")

        if verbose:
            print(response)
            for index, sample in enumerate(list(response.samples())):
                match, valid = self.encode(sample)
                print(index, ":", Solution(self.matching, match).is_stable(), match, valid)
        opt_en = self.get_optimal_energy(self.matching.size)
        solutions = []
        for sample, energy, occ in response.record:
            if energy == opt_en:
                match, valid = self.encode_qa(sample.tolist())
                if verbose and not valid:
                    print("Invalid encoding and valid energy!")
                solutions.append(Solution(self.matching, match))
        return solutions
Пример #4
0
def qubo_extractor(img,file_name):
	img_name, ext = file_name.split(".")
	(M,N) = img.shape[0:2]
	coupler_count = 0
	Q = {}
	for i in range(M):
		for j in range(N):
			foreground_node_id = (i*N*2)+(j*2)
			background_node_id = foreground_node_id+1
			#foreground qubit
			Q[(foreground_node_id,foreground_node_id)] = unary_potential(img,1,i,j)
			#background qubit
			Q[(background_node_id,background_node_id)] = unary_potential(img,0,i,j)
			#for qubits of same pixel - high cost should be given here to ensure both qubits are not open
			Q[(foreground_node_id,background_node_id)] = 10
			coupler_count += 1
			#for neighbors
			neighbors = find_neighbors(img,i,j)
			for k in neighbors:
				neighbor_foreground_node_id = (k[0]*N*2)+(k[1]*2)
				neighbor_background_node_id = neighbor_foreground_node_id+1
				#f.write('  '+ str(foreground_node_id) +' '+ str(neighbor_foreground_node_id) +' '+ str(f_1(img,i,j,k)) +'\n' )
				#f.write('  '+ str(background_node_id) +' '+ str(neighbor_foreground_node_id) +' '+ str(f_2(img,i,j,k)) +'\n' )
				#f.write('  '+ str(foreground_node_id) +' '+ str(neighbor_background_node_id) +' '+ str(f_2(img,i,j,k)) +'\n' )
				#f.write('  '+ str(background_node_id) +' '+ str(neighbor_background_node_id) +' '+ str(f_1(img,i,j,k)) +'\n' )
				#coupler_count += 1

	#print(Q)			
	
	
	response = QBSolv().sample_qubo(Q)
	result = list(response.samples())

	counter = 1
	out = []
	array = result[0]
	for i in array:
		mode = counter
		if(counter > (N*M*2)):
			continue
		if(mode%2 == 1):
			if array[i] == 1:
				out.append(int(255))
			else:
				out.append(0)
		counter += 1

		
	out=numpy.array(out)
	out = out.reshape(M,N)
	img_name, ext = file_name.split(".")

	if(os.path.isdir("result/" + img_name) != 1):
		call(["mkdir","result/" + img_name])

	rel_path = "result/" +img_name + "/"
	output_file_name = str(img_name) + "_out_python." + str(ext)
	file_path = rel_path + output_file_name
	scipy.misc.imsave(file_path,out)
Пример #5
0
def Solver(H,J):
    from dwave_qbsolv import QBSolv
    h=dict(enumerate(H.flatten(),0))
    j=dict(((i,j),J[i][j]) for i in range(len(J)) for j in range(len(J[0])) if i>j and J[i][j] !=0)
    response = QBSolv().sample_ising(h,j)
    sample=list(response.samples())
    value=list(sample[0].values())
    return value
Пример #6
0
    def solve(self, options):
        """
        Options:
            'solver' - see solver input to Qbsolve.sample, default 'tabu'
            'top_samples' - int, how many samples to print
            'visualize' - boolean,
            'verbosity' - int, default 0 (low)
        """
        DEFAULT_OPTIONS = {
            'solver': 'tabu',
            'top_samples': 1,
            'visualize': False,
            'verbosity': 0,
            'repititions': 5
        }
        complete_options = DEFAULT_OPTIONS.copy()
        complete_options.update(options)

        # get hamiltonian
        q = self.make_Q()

        # from np matrix to dwave representation
        Q = dimod.BinaryQuadraticModel.from_numpy_matrix(q)

        total_time = 0
        for _ in range(complete_options['repititions']):
            start_time = timer()

            # solve using QBSolv
            response = QBSolv().sample(Q,
                                       verbosity=complete_options['verbosity'],
                                       solver=complete_options['solver'])

            end_time = timer()
            if not complete_options['no_time']:
                print(f'time to solve: {end_time - start_time} s')
                total_time += end_time - start_time

            for sample_i, sample in enumerate(
                    response.samples()[0:complete_options['top_samples']]):
                X = self.sample_to_x_ij_matrix(sample)
                print(f'------- sample {sample_i} -------')
                print('solution is valid:', self.is_solution_valid(X))
                print('energy:', response.record.energy[sample_i])
                print('total U:', self.objective_value(X.flat))

                if complete_options['visualize']:
                    positions = self.sample_to_positions(sample)
                    self.plot_3d(positions)

        avg_time = total_time / complete_options['repititions']
        print(f'average time: {avg_time} s')
Пример #7
0
def Solver(H, J):
    from dwave_qbsolv import QBSolv
    from dwave.system.samplers import DWaveSampler
    from dwave.system.composites import EmbeddingComposite
    from dwave.cloud import Client
    import itertools
    import random
    sampler = EmbeddingComposite(
        DWaveSampler(token='DEV-34ebdd33f77f73904ed58bac612191ccdce89841'))
    h = dict(enumerate(H.flatten(), 0))
    j = dict(((i, j), J[i][j]) for i in range(len(J)) for j in range(len(J[0]))
             if i > j and J[i][j] != 0)
    response = QBSolv().sample_ising(h, j, solver=sampler)
    sample = list(response.samples())
    print(sample)
    return sample
Пример #8
0
 def solve_multi(self, verbose=True, num_repeats=100, target=None):
     if self.qubo is None:
         self.create_qubo()
     if self.mode == "np":  # more memory intensive
         response = QBSolv().sample(BinaryQuadraticModel.from_numpy_matrix(self.qubo), target=target)
     elif self.mode == "bqm":
         response = QBSolv().sample(self.qubo, num_repeats=num_repeats, target=target)
     else:
         raise Exception(f"mode: {self.mode} cannot be solved yet")
     if verbose:
         print(response)
     n = self.matching.size
     stable_energy = -3 / 2 * self.p1 * (n - 1) * n
     energies = list(response.data_vectors['energy'])
     samples = enumerate(list(response.samples()))
     allowed_samples = [sample for idx, sample in samples if energies[idx] == stable_energy]
     return [Solution(self.matching, self.encode(sample)) for sample in allowed_samples]
Пример #9
0
    def solve(self, verbose=False, num_repeats=100, target=None):
        if self.qubo is None:
            self.create_qubo()

        if self.mode == "np":  # more memory intensive
            response = QBSolv().sample(BinaryQuadraticModel.from_numpy_matrix(self.qubo), target=target)
        elif self.mode == "bqm":
            response = QBSolv().sample(self.qubo, num_repeats=num_repeats, target=target)
        else:
            raise Exception(f"mode: {self.mode} cannot be solved yet")
        if verbose:
            print(response)
        energies = list(response.data_vectors['energy'])
        min_en = min(energies)
        ret_match = self.encode(list(response.samples())[energies.index(min_en)])

        return Solution(self.matching, ret_match)
Пример #10
0
def qb(dets, thresh=None, confidence=None, ax=None):
    from dwave_qbsolv import QBSolv
    x1 = dets[:, 0]
    y1 = dets[:, 1]
    x2 = dets[:, 2]
    y2 = dets[:, 3]
    scores = dets[:, 4]
    if len(scores) == 0:
        return []
    elif len(scores) == 1:
        return [0]

    areas = (x2 - x1 + 1) * (y2 - y1 + 1)
    ious = {}  #np.zeros([len(x1), len(x1)])
    w2 = 0.4
    for i in range(len(x1)):
        xx1 = np.maximum(x1[i], x1)
        yy1 = np.maximum(y1[i], y1)
        xx2 = np.minimum(x2[i], x2)
        yy2 = np.minimum(y2[i], y2)

        w = np.maximum(0.0, xx2 - xx1 + 1)
        h = np.maximum(0.0, yy2 - yy1 + 1)
        inter = w * h
        ovr = inter / (areas[i] + areas - inter)
        for j in range(len(ovr)):
            if i == j:
                ious[i, i] = -(1 - w2) * scores[i]
                ious[i, j] += w2 * ovr[j]
            else:
                ious[i, j] = w2 * ovr[j]
    response = QBSolv().sample_qubo(ious, verbosity=0)
    samples = list(response.samples())[0]
    keep = []
    for i in range(len(x1)):
        if samples[i] == 1:
            keep.append(i)
    #if len(keep) == 0:
    #    keep_dets = np.ndarray((0, 4))
    #else:
    #    keep_dets = dets[keep]
    ## print(keep_dets)
    #return keep_dets
    return keep
Пример #11
0
def QBSolve_QC_solution(Qdict,
                        token="DEV-3fd7a21d8cf1afa9655ac1d7e9cb809bc3d7f7dc",
                        print_energy=False):
    """This function use QC to get solution dictionary"""

    endpoint = 'https://cloud.dwavesys.com/sapi'

    sampler = EmbeddingComposite(DWaveSampler(token=token, endpoint=endpoint))

    response = QBSolv().sample_qubo(Qdict, solver=sampler)

    if print_energy:
        print("energies=" + str(list(response.data_vectors['energy'])))

    qb_solution = list(response.samples())

    print("\n\nqb_solution:  ", qb_solution)

    return qb_solution
Пример #12
0
def QBSolve_classical_solution(Qdict, print_energy=False):
    """This function use classical QBSolve to get solution dictionary"""

    start = time.clock()

    response = QBSolv().sample_qubo(Qdict)

    qb_solution = list(response.samples())

    if print_energy:
        print("energies=" + str(list(response.data_vectors['energy'])))

    end = time.clock()

    time_taken = end - start

    print("Time taken by classical QBSolv: ", time_taken)

    return qb_solution
Пример #13
0
def qbsolve(Q, size=30):
    q_min = 0
    a_min = []
    response = QBSolv().sample_qubo(Q)
    for res in response.samples():
        a = np.empty(size)
        for key in res:
            a[key] = res[key]
        #------------------------------------------
        q = 0
        for i in xrange(size):
            for j in xrange(size):
                if (i, j) in Q:
                    q += Q[(i, j)] * a[i] * a[j]
        if q < q_min:
            q_min = q
            a_min = a

    return a_min, q_min
Пример #14
0
            J.setdefault((i, j), J_list[i][j])
    print('提取出h:')
    print(h)
    print('提取出J:')
    print(J)

    # 调用qbsolve第三方库得出退火模拟的结果
    count_all_first = 1000  # 输入调用第三方库的次数
    correct_count = 0
    count = 0
    q_truth_1 = 659  # 输入质因子
    q_truth_2 = 571  # 输入质因子
    for i in range(count_all_first):
        response = QBSolv().sample_ising(h, J)
        print("粒子自旋态:")
        spin = list(response.samples())
        print(spin)
        print("粒子自旋态对应能量值:")
        energy = list(response.data_vectors['energy'])
        print(energy)

        # 反推回去q的值
        q = 2 ** (len(q_list) + 1) + 1
        for j in range(len(q_list)):
            q_list[j] = (1 - spin[0][len(p_list) + j]) / 2
        for j in range(len(q_list)):
            q = q + q_list[j] * 2 ** (j + 1)
        print('q的值为')
        print(q)
        if q == q_truth_1 or q == q_truth_2:
            correct_count = correct_count + 1
Пример #15
0
def refine(G, sol, sp_size, obj, rmethod, spsolver, sp=None):
    global buildSpTime
    global solveTime
    start = time.perf_counter()
    if sp != None:
        subprob = sp
    elif rmethod == "spectral":
        subprob = spectralGainSubProb(G, sol, sp_size)
    elif rmethod == "pairwise":
        subprob = pairwiseSubProb(G, sol, sp_size)
    elif rmethod == "randpair":
        subprob = randPairSubProb(G, sol, sp_size)
    else:
        subprob = randSubProb(G, sp_size, sol)
    end = time.perf_counter()
    buildSpTime += (end - start)
    eGain = subprob[2]
    mapProbToSubProb = subprob[1]

    start = time.perf_counter()
    if spsolver == "qbsolv":
        Q = build_qubo(subprob[0])
        response = QBSolv().sample_qubo(Q)
        solution = response.samples()[0]

    elif spsolver == "qaoa":
        solution = qaoa(subprob[0])
    elif spsolver == "gurobi":
        solution = pyomo(subprob[0])
    elif spsolver == "sampling":
        solution = randSampleSolve(subprob[0])
    end = time.perf_counter()
    solveTime += (end - start)
    if timer:
        print(str(end - start) + "s solving subproblem")

    n = G.numberOfNodes()
    new_sol = {}
    changed = set()
    for i in range(n):
        new_sol[i] = solution[mapProbToSubProb[i]]
        if sol[i] != new_sol[i]:
            changed.add(i)

    new_obj = calc_obj(subprob[0], solution)
    rGain = new_obj - obj
    if showgain:
        print(str(eGain) + " expected gain, " + str(rGain) + " real gain")

    if new_obj > obj:
        for x in G.iterNodes():
            if sol[x] != new_sol[x]:
                if sol[x] == 0:
                    S.remove(x)
                    T.append(x)
                elif sol[x] == 1:
                    T.remove(x)
                    S.append(x)
        if rmethod == 'pairwise':
            for x in changed:
                for y in G.iterNeighbors(x):
                    if new_sol[x] == new_sol[y]:
                        mapGain[x] -= 2 * G.weight(x, y)
                        mapGain[y] -= 2 * G.weight(x, y)
                    if new_sol[x] != new_sol[y]:
                        mapGain[x] += 2 * G.weight(x, y)
                        mapGain[y] += 2 * G.weight(x, y)
        return (new_sol, new_obj, subprob)

    else:
        return (sol, obj, subprob)
Пример #16
0
        elif i==j:
            D[(i,j)]= Coefficients[i,j]
# Solve the Puzzle
use_qpu=True
if use_qpu:
    solver_limit = 256
    G = nx.complete_graph(solver_limit)
    system = DWaveSampler(token='DEV-6189564036d19f88b3a555b4175a353d6d2c0218')
    embedding = minorminer.find_embedding(D.keys(), system.edgelist)
    print(embedding)
    res = QBSolv().sample_qubo(D, solver=FixedEmbeddingComposite(system, embedding), solver_limit=solver_limit,token='DEV-6189564036d19f88b3a555b4175a353d6d2c0218', num_reads=20)
    #Emb = EmbeddingComposite(DWaveSampler(token='DEV-6189564036d19f88b3a555b4175a353d6d2c0218'))
    #res = Emb.sample_qubo(D, num_reads=10000)
else:
    res = QBSolv().sample_qubo(D,num_repeats=20)
samples = list(res.samples())
energy = list(res.data_vectors['energy'])
print(samples)
print(energy)
# Represent the Results
for i in range(len(samples)):
    result = samples[i]
    output = []
    # ignore ancillary variables, which are all negative, only get positive bits
    for x in range(r*m*n):
        output.append(result[x])
    output = np.array(output)#DisplayOut(In,np.array(output),r)
    F=output.reshape(r,m*n)
    output=mapseq(F)
    print("energy: {}_____________________________".format(energy[i]))
    print(output)
Пример #17
0
    #Weights in nodes (for right node states)
    for node in G.nodes:
        for i in range(num_colors - 1):
            for j in range(num_colors - 1 - i):
                Q[(num_colors * node + i, num_colors * node + 1 + i + j)] = v2

    # +2 for all wrong edges (has a 1 on the same place)
    for edge in G.edges:
        for i in range(num_colors):
            Q[(num_colors * edge[0] + i, num_colors * edge[1] + i)] = v3

    print("Q = " + str(Q))

    response = QBSolv().sample_qubo(Q)

    samples = list(response.samples())

    print("Solution = " + str(samples))
    print("Energy = " + str(list(response.data_vectors['energy'])))

    energy_test = v1 * n_nodes

    if response.data_vectors['energy'][0] == energy_test:
        plt.title('Successfully solved with ' + str(num_colors) + ' colors')
        solving = False
    else:
        if num_colors == 10:
            plt.title('Cannot be solved with 10 or less colors')
            solving = False
        else:
            num_colors += 1
Пример #18
0
def solve_with_qbsolv(Q):
    response = QBSolv().sample_qubo(Q, num_repeats=1000)
    return response.samples()[0]
Пример #19
0
def Solver(H, J):
    from dwave_qbsolv import QBSolv
    response = QBSolv().sample_ising(H, J)
    sample = list(response.samples())
    return sample
Пример #20
0
import math

#number of variables
n = 12
file = open("rou12.QUBO", "rb")
QUBO = pickle.load(file)
file.close()
file = open("rou12.flow", "rb")
flows = pickle.load(file)
file.close()
file = open("rou12.dist", "rb")
distances = pickle.load(file)
file.close()

result = QBSolv().sample_qubo(QUBO, num_repeats=50, verbosity=0, solver='tabu')
samples = list(result.samples())
perm = np.zeros((n, ), dtype=int)
solution = ""
cost = 0
for i in range(n):
    for j in range(n):
        if samples[0][(i * n) + j] == 1:
            solution = solution + " " + str(j + 1)
            perm[i] = j + 1

print("solution", ":", solution)
for i in range(n):
    for j in range(n):
        cost += distances[i, j] * flows[int(perm[i] - 1), int(perm[j]) - 1]
print("cost:", cost)
Пример #21
0
                 (cost_poly.coeff_monomial(X[i]**1) if (i == j) else 0))
        for i in range(num_qubits) for j in range(i, num_qubits)}

# execution on D-Wave simulator
from dwave_qbsolv import QBSolv

result_dwave = QBSolv().sample_qubo(Qubo)

#####################################
###### END EXECUTION ON D WAVE #####
#####################################

##########################
###### DATA TRANSFER #####
##########################

# take first result
# better: check for index with lowest energy
samples = list(result_dwave.samples())[0]

# select ids of all selected edges
ids = []
for i in range(len(samples)):
    if (samples[i] == 1):
        ids.append(i)
print(json.dumps({"ids": ids}))

##############################
###### END DATA TRANSFER #####
##############################
Пример #22
0
            QUBO[(v, j)] = QUBO[(v, j)] + (2.0) * prefactor

# Prints QUBO Matrix to console (for debugging purpose)
# for v in range(0, length_of_QUBO):
#     for j in range(v, length_of_QUBO):
#         print(" %s, %s : %s " % (v, j, QUBO[(v, j)]))

# Call QBSolv
answer = QBSolv().sample_qubo(QUBO,
                              num_repeats=num_repeats,
                              seed=seed,
                              algorithm=algorithm,
                              verbosity=verbosity,
                              timeout=timeout,
                              solver_limit=solver_limit,
                              solver=solver,
                              target=target,
                              find_max=find_max)

# # Decode QBSolv answer
samples = list(answer.samples())
print "samples", samples
print "energies", list(answer.data_vectors['energy'])

# # Decode answer and print it to the console
for i in range(len(samples)):
    print "Solution Nr", i
    print samples[i]
    for j in range(len(samples[0])):
        if samples[i][j] == 1:
            print facility_to_location[j]
import itertools

import networkx as nx

from dwave_qbsolv import QBSolv
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import FixedEmbeddingComposite
import minorminer

# define (sub)problem size
solver_limit = 3
qubo_size = 4

# find embedding of subproblem-sized complete graph to the QPU
G = nx.complete_graph(solver_limit)
system = DWaveSampler()
embedding = minorminer.find_embedding(G.edges, system.edgelist)

# solve a random problem
Q = {
    t: random.uniform(-1, 1)
    for t in itertools.product(range(qubo_size), repeat=2)
}
response = QBSolv().sample_qubo(Q,
                                solver=FixedEmbeddingComposite(
                                    system, embedding),
                                solver_limit=solver_limit)
print("Q=" + str(Q))
print("samples=" + str(list(response.samples())))
print("energies=" + str(list(response.data_vectors['energy'])))
Пример #24
0
def Solver(H, J):
    response = QBSolv().sample_ising(H, J)
    sample = list(response.samples())
    return sample
Пример #25
0
def main(argv):

    file = open(argv[1])
    lines = file.readlines()
    file.close()

    #delete any comments and empty lines
    for i in range(len(lines) - 1, -1, -1):
        #delete the newline character at the end
        temp = lines[i].split("\n")
        lines[i] = temp[0]

        temp = lines[i].split(" #")
        lines[i] = temp[0]
        temp = lines[i].split("#")
        lines[i] = temp[0]

        if (lines[i] is ""):
            tmp = lines.pop(i)

    numOfNodes = int(lines[0])

    #initialize graph and nodes
    graph = Graph()
    for i in range(0, numOfNodes):
        node = Node(i)
        graph.addNode(node)

    #initialize edges
    nextLine = 1
    numOfEdges = 0
    for i in range(0, numOfNodes):
        nodeIDs = lines[nextLine + i].split(" ")
        for j in range(0, len(nodeIDs)):
            nodeA = graph.getNodeWithID(i)
            nodeB = graph.getNodeWithID(int(nodeIDs[j]))

            edge_existing = nodeA.getEdgeWithNode(nodeB)
            if not (edge_existing is None):
                continue
            edge_existing = nodeB.getEdgeWithNode(nodeA)
            if not (edge_existing is None):
                continue

            edge = Edge(numOfEdges, nodeA, nodeB)
            graph.addEdge(edge)
            numOfEdges = numOfEdges + 1

    #print the edges
    # edges = graph.getEdges()
    # for i in range(0, len(edges)):
    # print(str(edges[i].getID()) + "  A: " + str(edges[i].getNodes()[0].getID()) + "  B: " + str(edges[i].getNodes()[1].getID()))

    nextLine = nextLine + numOfNodes
    numOfCars = int(lines[nextLine])
    nextLine = nextLine + 1

    #get original car routes for each car
    carRoutes = []
    for i in range(0, numOfCars):
        carRoutes.append([])

    for i in range(0, numOfCars):
        nodeIDs = lines[nextLine + i].split("-")
        route = []
        for j in range(0, len(nodeIDs) - 1):
            nodeA = graph.getNodeWithID(int(nodeIDs[j]))
            nodeB = graph.getNodeWithID(int(nodeIDs[j + 1]))
            edge = nodeA.getEdgeWithNode(nodeB)
            route.append(edge)
        carRoutes[i].append(route)
    nextLine = nextLine + numOfCars

    #get the alternate routes
    numOfAlternateRoutes = 3
    for i in range(0, numOfCars * (numOfAlternateRoutes - 1)):
        carNum = int(lines[nextLine + i].split(" ")[0])
        nodeIDs = (lines[nextLine + i].split(" ")[1]).split("-")
        route = []
        for j in range(0, len(nodeIDs) - 1):
            nodeA = graph.getNodeWithID(int(nodeIDs[j]))
            nodeB = graph.getNodeWithID(int(nodeIDs[j + 1]))
            edge = nodeA.getEdgeWithNode(nodeB)
            route.append(edge)
        carRoutes[carNum].append(route)

    Q = getQuboMatrix(carRoutes, numOfAlternateRoutes)

    response = QBSolv().sample_qubo(Q)
    result = list(response.samples())
    result = result[0]
    resultingEnergy = list(response.data_vectors['energy'])
    resultingEnergy = resultingEnergy[0]

    # print("samples=" + str(result))
    # print("energies=" + str(list(response.data_vectors['energy'])))

    print("roads taken:")
    for i in range(0, len(result)):
        if (result[i] == 1):
            print("car " + str((i // numOfAlternateRoutes) + 1) + ": route " +
                  str((i % numOfAlternateRoutes) + 1))

    print("Resulting energy: " + str(resultingEnergy))
Пример #26
0
def sample_from_distance_matrix(dist_matrix,
                                dist_mul=1,
                                const_mul=8500,
                                start=None,
                                end=None,
                                **kwargs):
    """Sample TSP qubo from given distance matrix and return lowest-energy sdolution.

    This is basically the same as :py:func:`sample_from_locations` except it skips
    calculation of distance matrix (which is instead given as parameter) and can
    take into account starting and ending node.
    """
    dist_matrix = np.array(dist_matrix)
    number_of_locations = dist_matrix.shape[0]
    max_distance = np.max(dist_matrix)
    dist_matrix = dist_matrix / max_distance

    qubo = construct_qubo(dist_matrix, dist_mul, const_mul)
    use_dwave = kwargs.get('use_dwave', False)
    token = kwargs.get('dwave_token', None)
    solver = kwargs.get('solver', None)

    if 'use_dwave' in kwargs:
        del kwargs['use_dwave']
        del kwargs['dwave_token']
    import gc

    if use_dwave:
        try:
            num_reads = 1000
            if number_of_locations > 7:
                num_reads = 2000
            print("Start solving using D-Wave!")
            # solver = EmbeddingComposite(DWaveSampler(token=token, endpoint=DWAVE_ENDPOINT))
            result = solver.sample_qubo(qubo,
                                        num_reads=num_reads,
                                        chain_strength=const_mul * 2)
            info = {
                "total_time": result.info['timing']['total_real_time'] / 10e3,
                "machine": "DWAVE 2000Q"
            }
        except Exception as e:
            print(e)
            print("D-Wave failed, switched to QBSolv!")
            result = QBSolv().sample_qubo(qubo, **kwargs)
            info = {"machine": "local"}
    else:
        print("Start solving using QBSolv")
        result = QBSolv().sample_qubo(qubo, **kwargs)
        info = {"machine": "local"}
    print("Got answer!")
    route = route_from_sample(next(iter(result.samples())),
                              number_of_locations, start, end)
    mileage = calculate_mileage(dist_matrix * max_distance, route)
    info['mileage'] = mileage
    print("Problem solved!")
    energy = result.data_vectors['energy'][0]
    del solver
    del result
    gc.collect()
    return TSPSolution(route, energy, mileage, info)