Skip to content

Instantly share code, notes, and snippets.

@hariby
Created March 3, 2022 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hariby/334168a0fbacd2c493b8577319c5b901 to your computer and use it in GitHub Desktop.
Save hariby/334168a0fbacd2c493b8577319c5b901 to your computer and use it in GitHub Desktop.
Amazon Braket Hybrid Jobs with D-Wave Quantum Annealer
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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.
import os
import numpy as np
from braket.aws import AwsDevice
from braket.circuits import Circuit
from braket.jobs import save_job_result
import json
from braket.aws import AwsDevice, AwsSession
from braket.ocean_plugin import BraketSampler, BraketDWaveSampler
import networkx as nx
import dwave_networkx as dnx
from dimod.binary_quadratic_model import BinaryQuadraticModel
from dwave.system.composites import EmbeddingComposite
from collections import defaultdict
def create_graph():
# ------- Set up our graph -------
# Create empty graph
G = nx.Graph()
# Add edges to the graph (also adds nodes)
G.add_edges_from([(1,2),(1,3),(2,4),(3,4),(3,5),(4,5)])
# plot graph
pos = nx.spring_layout(G)
# ------- Set up the QUBO dictionary -------
# Initialize our Q matrix
Q = defaultdict(int)
# Update Q matrix for every edge in the graph
for u, v in G.edges:
Q[(u,u)]+= -1
Q[(v,v)]+= -1
Q[(u,v)]+= 2
return Q
def load_hyperparameters():
"""Load the Hybrid Job hyperparameters"""
hp_file = os.environ["AMZN_BRAKET_HP_FILE"]
with open(hp_file) as f:
hyperparams = json.load(f)
return hyperparams
print("Test job started!!!!!")
# Use the device declared in the creation script
device = os.environ["AMZN_BRAKET_DEVICE_ARN"]
hyperparams = load_hyperparameters()
chainstrength = int(hyperparams["chainstrength"])
numruns = int(hyperparams["numruns"])
n_iterations = int(hyperparams["n_iterations"])
set_list = []
cut_list = []
energy_list = []
Q = create_graph()
for _ in range(n_iterations):
sampler = BraketDWaveSampler(s3_destination_folder=(AwsSession().default_bucket(), 'd-wave/hybrid-jobs'), device_arn=device)
sampler = EmbeddingComposite(sampler)
response = sampler.sample_qubo(Q, chain_strength=chainstrength, num_reads=numruns)
energies = iter(response.data())
print('-' * 60)
print('{:>15s}{:>15s}{:^15s}{:^15s}'.format('Set 0','Set 1','Energy','Cut Size'))
print('-' * 60)
for line in response:
S0 = [k for k,v in line.items() if v == 0]
S1 = [k for k,v in line.items() if v == 1]
E = next(energies).energy
print('{:>15s}{:>15s}{:^15s}{:^15s}'.format(str(S0),str(S1),str(E),str(int(-1*E))))
set_list.append((str(S0),str(S1)))
cut_list.append(int(-1*E))
energy_list.append(E)
save_job_result({"set": set_list, "cut": cut_list, "energy": energy_list})
print("Test job completed!!!!!")
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@hariby
Copy link
Author

hariby commented Mar 3, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment