Пример #1
0
def QBSolve_quantum_solution(Q, times_list, token, annealing_time, print_energy=False):
    """This function use QC to get solution dictionary"""

    Qdict = Q_dict(Q)
    # print("QDICT: ", Qdict)
    # endpoint = 'https://cloud.dwavesys.com/sapi'

    # bqm = dimod.BinaryQuadraticModel.from_qubo(Qdict)

    # print("BQM: ", bqm)

    print("ACCESSING QUANTUM COMPUTER . . . . .")
    print("Anneal time: ", annealing_time)
    sampler = LeapHybridSampler(token=token)

    start = time.clock()

    # try:

    response = sampler.sample_qubo(Qdict, qpu_params={'annealing_time': annealing_time})

    timing_dict = response.info
    # print("\n\n\n\nTIMING INFO: ", timing_dict)

    qc_time = timing_dict["qpu_access_time"]

    qc_time_list.append(qc_time)
    print("\n\n\n\n\nQC TIMES UHUHUHUHUHHUHU", qc_time_list)

    end = time.clock()

    # print("INFO: ", response.info)
    print("RESPONSE: ", response)

    # except ValueError:
    #     print("\n\nEXCEPTION FOUND ...............\n")
    #     # response = QBSolv.QBSolv().sample_qubo(Qdict, solver=sampler)
    #     response = QBSolv.QBSolv().sample_qubo(Qdict)

    # print("RESPONSE: ", response)

    print("energies=" + str(list(response.data_vectors['energy'])))
    print("num_occurence=" + str(list(response.data_vectors['num_occurrences'])))

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

    time_taken = end - start

    times_list.append(time_taken)

    print("Time taken by QPU: ", time_taken)

    qb_solution = list(response.samples())

    qb_solution_list = list(qb_solution[0].values())

    return qb_solution_list
Пример #2
0
def generate_stars(N: int, nstars: int, annealer="neal", num_reads=100):
    """
    Generate valid star positions on grid.
    Return a list of positions and an np.array.
    
    Annealer may be:
        1. 'neal' (simulated);
        2. 'leap' (real)."""

    g = 1
    Q = constraint_two_dont_touch(N)
    regions = [*row_regions(N), *column_regions(N)]
    for region in regions:
        Q = Q + g * region_constraint(region, nstars)
    
    if annealer == 'neal':
        sampler = neal.SimulatedAnnealingSampler()
        sampleset = sampler.sample_qubo(Q, num_reads=num_reads)
        
    elif annealer == 'leap':  # Go to DWave
        sampler = LeapHybridSampler()
        sampleset = sampler.sample_qubo(Q)
        
    else:
        raise Exception(f"Annealer {annealer} not recognized.")

        
    minimum_theo = -2 * N * nstars**2 * g
    
    valid_samples = []
    
    sorted_records = sorted(sampleset.record, key=lambda r: r.energy)
    variables = sampleset.variables
    
    for record in sorted_records:
        sample = {x_ij: value for x_ij, value in zip(variables, record.sample)}
        energy = record.energy

        cond_1 = confirm_solution_stars(sample, regions, nstars)
        cond_2 = abs(energy - minimum_theo) < 1e-6

        if not cond_1 | cond_2:
            break
            
        # Return a list of positions and an np.array.
        yield star_solutions(N, sample)
Пример #3
0
    def quantum_tsp(self):
        sampler = LeapHybridSampler()

        # Get a QUBO representation of the problem
        Q = self.quantum_tsp_qubo()

        # use the sampler to find low energy states
        response = sampler.sample_qubo(Q)
        sample = response.first.sample

        route = [None] * len(self.G)
        for (city, time), val in sample.items():
            if val:
                route[time] = city

        if self.start is not None and route[0] != self.start:
            # rotate to put the start in front
            idx = route.index(self.start)
            route = route[idx:] + route[:idx]

        return route
Пример #4
0
def solve_puzzle(N, nstars, grid, annealer="neal", num_reads=10):
    Q = constraint_two_dont_touch(N)

    regions = [
        *region_lists(grid),
        *row_regions(N),
        *column_regions(N),
    ]

    g = 1
    for region in regions:
        Q = Q + g * region_constraint(region, nstars)

    # Create Sampler

    if annealer == 'neal':
        sampler = neal.SimulatedAnnealingSampler()
        sampleset = sampler.sample_qubo(Q, num_reads=num_reads)

    elif annealer == 'leap':  # Go to DWave
        sampler = LeapHybridSampler()
        sampleset = sampler.sample_qubo(Q)

    else:
        raise Exception(f"Annealer {annealer} not recognized.")

    minimum_energy = theoretical_minimum(N, nstars, g)

    sorted_records = sorted(sampleset.record, key=lambda r: r.energy)
    variables = sampleset.variables
    for record in sorted_records:
        sample = {x_ij: value for x_ij, value in zip(variables, record.sample)}
        energy = record.energy

        is_solution = confirm_solution_stars(sample, regions, nstars)

        if is_solution:
            _, solution = star_solutions(N, sample)
            return solution
Пример #5
0
def generate_regions(N: int, nstars: int, star_positions: list, star_grid: np.array,  annealer="neal", num_reads=100):
    # Build Star Finder QUBO
    g1, g2, g3, g4 = 1, 1, 1, 1
    color_size = np.array([N]*N) #Number of sites per color
    Q_reg_1 = g1 * constraint_sum_of_stars(N, nstars, star_positions)
    Q_reg_2 = g2 * constraint_unique_color(N)
    Q_reg_3 = g3 * constraint_contiguous(N)
    Q_reg_4 = g4 * constraint_sum_of_sites(N,color_size)
    Q_reg = Q_reg_1 + Q_reg_2 + Q_reg_3 + Q_reg_4
    
    if annealer == 'neal':
        sampler = neal.SimulatedAnnealingSampler()
        sampleset = sampler.sample_qubo(Q_reg, num_reads=num_reads)
        
    elif annealer == 'leap':  # Go to DWave
        sampler = LeapHybridSampler()
        sampleset = sampler.sample_qubo(Q_reg)
        
    else:
        raise Exception(f"Annealer {annealer} not recognized.")

    upper_bound = -g1*N*nstars**2 -g2*N**2 -g4*np.sum(color_size**2)
    lower_bound = upper_bound - g3*4*N**2
      
    # Confirm Solution of Regions
    sample_star = {x(i, j): value for (i, j), value in np.ndenumerate(star_grid)}
    
    sorted_records = sorted(sampleset.record, key=lambda r: r.energy)
    variables = sampleset.variables

    for record in sorted_records:
        sample = {x_ij: value for x_ij, value in zip(variables, record.sample)}
        energy = record.energy
        grid = grid_solutions(N, sample)
        regions = [*region_lists(grid), *row_regions(N), *column_regions(N)]
        
        if confirm_solution_regions(sample_star, grid, nstars):
            yield grid
H_time = Constraint(normalize(sum((sum(q[i][t] for i in range(N-1))-1)**2 for t in range(N-1))), 'time')

# Express objective function and compile it to model
H = H_cost + Placeholder('lam') * (H_city + H_time)
model = H.compile()


# --- Solve QUBO ---

# Get the QUBO matrix from the model
feed_dict = {'lam':5.0}  # the value of constraint
qubo, offset = model.to_qubo(feed_dict=feed_dict)

# Run QUBO on Leap's Hybrid Solver (hybrid_v1)
sampler = LeapHybridSampler(token='') 
response = sampler.sample_qubo(qubo)
sample = response.record['sample'][0]

# decode the solution and check if constrains are satisfied
sample_dict = {idx: sample[i] for i,idx in enumerate(response.variables)}
decoded, broken, energy = model.decode_solution(sample_dict, 'BINARY', feed_dict=feed_dict)  
if broken == {}:
    print('The solution is valid')
else:
    print('The solution is invalid')


# --- Visualize the result ---

# Create an array which shows traveling order from the solution
solution = sample.reshape(N-1, N-1)
            Q[(return_QUBO_Index(v,j), return_QUBO_Index(w,j))] += 2*A
            Q[(return_QUBO_Index(w,j), return_QUBO_Index(v,j))] += 2*A

# Objective that minimizes distance
for u in range(Total_Number_Houses):
     for v in range(Total_Number_Houses):
        if u!=v:
            for j in range(Total_Number_Houses):
                Q[(return_QUBO_Index(u,j), return_QUBO_Index(v,(j+1)%Total_Number_Houses))] += B*D[u][v]

# Run the QUBO using qbsolv (classically solving)
#resp = QBSolv().sample_qubo(Q)

# Use LeapHybridSampler() for faster QPU access
sampler = LeapHybridSampler()
resp = sampler.sample_qubo(Q)

# First solution is the lowest energy solution found
sample = next(iter(resp))    

# Display energy for best solution found
print('Energy: ', next(iter(resp.data())).energy)

# Print route for solution found
route = [-1]*Total_Number_Houses
for node in sample:
    if sample[node]>0:
        j = node%Total_Number_Houses
        v = (node-j)/Total_Number_Houses
        route[j] = int(v)
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License
from dwave.system import LeapHybridSampler
sampler = LeapHybridSampler()

GAMMA = 1.5
#exactsolver = dimod.ExactSolver()

Q = {('X1','X2'): 2 * GAMMA - 2,
     ('X1','X3'): 2 * GAMMA - 2,
     ('X1','X4'): 2 * GAMMA - 2,
     ('X2','X3'): 2 * GAMMA - 2,
     ('X2','X4'): 2 * GAMMA - 2,
     ('X3','X4'): 2 * GAMMA - 2,
     ('X1','X1'): 3 - 3 * GAMMA,
     ('X2','X2'): 3 - 3 * GAMMA,
     ('X3','X3'): 3 - 3 * GAMMA,
     ('X4','X4'): 3 - 3 * GAMMA}

results = sampler.sample_qubo(Q)

# print the results
for sample, energy in results.data(['sample', 'energy']):
    print(sample, energy)
Пример #9
0
#final hamiltonian
H = (min_sigx / scale_down + lambda1 * select_n + lambda2 * expectedReturn)

model = H.compile()
qubo, offset = model.to_qubo()
useQPU = True

num_samples_hybrid = 40
#number of times hybrid solver is used

if useQPU:
    for _ in range(num_samples_hybrid):
        # start = time.time()
        sampler = LeapHybridSampler()
        response = sampler.sample_qubo(qubo)
        sample = response.first.sample
        final_sigx = 0
        for i in range(N):
            for j in range(N):
                final_sigx += sample['arr[{}]'.format(i)] * sample[
                    'arr[{}]'.format(j)] * sigma[i][j]
        print(final_sigx)

        # end = time.time()
        # print(end - start,"s")

else:
    sampler = neal.SimulatedAnnealingSampler()
    response = sampler.sample_qubo(qubo, num_sweeps=1000, num_reads=1000)
Пример #10
0
Q = defaultdict(int)

for ele in range(0, len(S)):
    c = c + S[ele]

#Linear value i.e diagonal values
for ele in range(0, len(S)):
    Q[ele, ele] = S[ele]*(S[ele]-c)

#Quadratic value i.e off-diagonal values

for i in range(0, len(S)):
    for j in range(0, len(S)):
        if(i!=j):
            Q[i, j] = S[i]*S[j]

print("\n\n---Create Q %s seconds ---" % (time.time() - start_time))

solve_start = time.time()

sampleset = sampler.sample_qubo(Q)

print("\n\n---Solved in %s seconds ---" % (time.time() - solve_start))

print(sampleset)

for sample in sampleset.samples():
    print(sample)

print("\n\n---Execution end %s seconds ---" % (time.time() - start_time))
Пример #11
0
def solve(
    N,  # Number of data points
    K,  # Number of clusters
    dist_matrix,  # NxN matrix with distances between data points
    gamma_distinct=None,  # Coefficent for the penalty of being
    gamma_multiple=None,  # Coefficient for the penalty of being assigned to multiple clusters (illegal); should be very high
    target_goal=None,  # Target equal value for each cluster; by default, it's N//K
    point_weights=None,  # N-element Weight Vector for the points in the equal size constraint; by default , we assume all ones
):
    if target_goal is None:
        target_goal = N // K

    if point_weights is None:
        point_weights = np.ones(N)

    if gamma_distinct is None:
        gamma_distinct = np.max(dist_matrix)

    if gamma_multiple is None:
        gamma_multiple = np.max(
            dist_matrix
        )  # weight bigger than sum of all distances, not worth taking more than one

    group_matrix = Array.create("x", shape=(N, K), vartype="BINARY")

    distinct_size_penalty = Placeholder("gamma_distinct")
    multiple_assignment_penalty = Placeholder("gamma_multiple")
    target = Placeholder("target_goal")

    all_terms = []

    # Penalty for being assigned to multiple clusters
    for i in range(N):
        single_asignment_constraint = (1 - sum(group_matrix[i, :]))**2
        all_terms.append(multiple_assignment_penalty *
                         single_asignment_constraint)

    # Penalty for exceding equal number of members per cluster
    for j in range(K):
        cluster_member_constraint = (
            target - sum(point_weights * group_matrix[:, j]))**2
        all_terms.append(distinct_size_penalty * cluster_member_constraint)

    # Adding objective for distances. Must minimize distances in the same group
    for i in range(N):
        for j in range(i + 1, N):
            same_group_combinations = group_matrix[i, :] * group_matrix[j, :]
            all_terms.append(dist_matrix[i, j] * sum(same_group_combinations))

    # Generate QUBO from equation that represents the DQM
    equation = sum(all_terms)
    model = equation.compile()
    Q, offset = model.to_qubo(
        feed_dict={
            "gamma_distinct": gamma_distinct,
            "gamma_multiple": gamma_multiple,
            "target_goal": target_goal,
        })

    # Call D-Wave solver
    sampler = LeapHybridSampler()

    answer = sampler.sample_qubo(Q)

    best_answer = list(answer.data(["sample", "energy"]))[0].sample

    # Utility function to map from QUBO temp matrix label to integer
    def matrix_entry_to_pair(val):
        _, i, j = val.replace("[", " ").replace("]", " ").split()
        return (int(i), int(j))

    cluster_result = [
        matrix_entry_to_pair(k) for k, v in best_answer.items() if v == 1
    ]

    label_result = [p[1] for p in sorted(cluster_result)]

    return label_result
Пример #12
0
#     https://github.com/dwave-examples/simple-ocean-programs/blob/master/Basic_Programs/general_program_qubo.py


# Import the functions and packages that are used
from dwave.system import EmbeddingComposite, DWaveSampler, LeapHybridSampler
from neal import SimulatedAnnealingSampler

# Define the problem as a Python dictionary
Q = {('B','B'): 1, 
    ('K','K'): 1, 
    ('A','C'): 2, 
    ('A','K'): -2, 
    ('B','C'): -2}

###### D-WaveのQPU Samplerを用いる方法です。(Leap時間を消費します!)
# Define the sampler that will be used to run the problem
sampler = EmbeddingComposite(DWaveSampler())

# Run the problem on the sampler and print the results
sampleset = sampler.sample_qubo(Q, num_reads = 10)
print(sampleset)

###### Leap Hybrid samplerを用いる方法です。(Leap時間を消費します!)
sampler_hybrid = LeapHybridSampler()
sampleset_hybrid = sampler_hybrid.sample_qubo(Q,time_limit=3)
print(sampleset_hybrid)

###### Simulated Annealing samplerを用いる方法です。(Leap時間を消費しません)
sampler_neal = SimulatedAnnealingSampler()
sampleset_neal = sampler_neal.sample_qubo(Q, num_reads=10)
print(sampleset_neal.aggregate())