def find_isomorphism(G1, G2): """Search for isomorphism between two graphs Args: G1 (networkx.Graph) G2 (networkx.Graph) Returns: If no isomorphism is found, returns None. Otherwise, returns dict with keys as nodes from graph 1 and values as corresponding nodes from graph 2. """ if G1.number_of_nodes() != G2.number_of_nodes(): return None dqm = create_dqm(G1, G2) sampler = LeapHybridDQMSampler() results = sampler.sample_dqm(dqm, label='Example - Circuit Equivalence') best = results.first # Note: with this formulation, the ground state energy for an # isomorphism is -A*N, where A is the penalty coefficient # associated with the H_A term, currently assumed to be 1. if np.isclose(best.energy, -G1.number_of_nodes()): G2_nodes = list(G2.nodes) return {k: G2_nodes[i] for k, i in best.sample.items()} else: # Isomorphism not found return None
def find_isomorphism(G1, G2): """Search for isomorphism between two graphs Args: G1 (networkx.Graph) G2 (networkx.Graph) Returns: If no isomorphism is found, returns None. Otherwise, returns dict with keys as nodes from graph 1 and values as corresponding nodes from graph 2. """ if G1.number_of_nodes() != G2.number_of_nodes(): return None dqm = create_dqm(G1, G2) sampler = LeapHybridDQMSampler() results = sampler.sample_dqm(dqm, label='Example - Circuit Equivalence') best = results.first if np.isclose(best.energy, 0.0): G2_nodes = list(G2.nodes) return {k: G2_nodes[i] for k, i in best.sample.items()} else: # Isomorphism not found return None
def solve(adj_nodes, adj_edges, even_dist=False): dqm = DiscreteQuadraticModel() for i in adj_nodes: dqm.add_variable(NURSES, label=i) # classic graph coloring constraint that no two adjacent nodes have the same color for i0, i1 in adj_edges: dqm.set_quadratic(i0, i1, {(c, c): LAGRANGE for c in range(NURSES)}) shifts_per_nurse = DAYS * SHIFTS // NURSES if even_dist: # we should ensure that nurses get assigned a roughly equal amount of work for i in range(NURSES): for index, j in enumerate(adj_nodes): dqm.set_linear_case( j, i, dqm.get_linear_case(j, i) - LAGRANGE * (2 * shifts_per_nurse + 1)) for k_index in range(index + 1, len(adj_nodes)): k = adj_nodes[k_index] dqm.set_quadratic_case( j, i, k, i, LAGRANGE * (dqm.get_quadratic_case(j, i, k, i) + 2)) # some nurses may hate each other, so we should do out best to not put them in the same shift! for d in range(DAYS): for s in range(SHIFTS): for l1 in range(NURSES_PER_SHIFT): for l2 in range(l1 + 1, NURSES_PER_SHIFT): j = f"l{l1}_d{d}_s{s}" k = f"l{l2}_d{d}_s{s}" for conflict in CONFLICTS: for n1 in conflict: for n2 in conflict: if n1 == n2: continue dqm.set_quadratic_case( j, n1, k, n2, LAGRANGE2 * (dqm.get_quadratic_case(j, n1, k, n2) + 10)) sampler = LeapHybridDQMSampler(token=API_TOKEN) sampleset = sampler.sample_dqm(dqm, time_limit=10) sample = sampleset.first.sample energy = sampleset.first.energy return sample, energy
def run_hybrid_solver(dqm): """Solve DQM using hybrid solver through the cloud.""" print("\nRunning hybrid sampler...") # Initialize the DQM solver sampler = LeapHybridDQMSampler() # Solve the problem using the DQM solver sampleset = sampler.sample_dqm(dqm, label='Example - Map Coloring') return sampleset
def find_equivalence(C1, C2): """Search for equivalence between two circuits This requires that the corresponding graphs are isomorphic and that matched nodes are "equivalent". In particular, transistor types must match. Args: C1 (Circuit) C2 (Circuit) Returns: If no equivalence is found, returns None. Otherwise, returns dict with keys as nodes from graph 1 and values as corresponding nodes from graph 2. """ if C1.G.number_of_nodes() != C2.G.number_of_nodes(): return None dqm = create_dqm(C1.G, C2.G) sampler = LeapHybridDQMSampler() results = sampler.sample_dqm(dqm, label='Example - Circuit Equivalence') if not np.isclose(results.first.energy, -C1.G.number_of_nodes()): return None G2_nodes = list(C2.G.nodes) for sample, energy in results.data(fields=['sample', 'energy']): if np.isclose(energy, -C1.G.number_of_nodes()): # Now check that the transistor types match mapping = {k: G2_nodes[i] for k, i in sample.items()} valid = True for n1, n2 in mapping.items(): if ('nMOS' in n1 and 'nMOS' not in n2) or ('pMOS' in n1 and 'pMOS' not in n2): valid = False break if valid: return mapping else: # Sample is not an isomorphism return None return None
def solveSudoku(dqm, G): ''' This method solves the sudoku and also verify the result Parameters: dqm : Discrete Quadratic Model object G : networkx graph object, which represents the modelled graph Returns: valid : Boolean variable which tells if the solution is valid or invalid solution : 2D solution list to our Sudoku problem ''' sampler = LeapHybridDQMSampler() sampleset = sampler.sample_dqm(dqm) sample = sampleset.first.sample energy = sampleset.first.energy valid = True for edge in G.edges: i, j = edge if (sample[i] == sample[j]): valid = False break print("Solution :", sample) print("Solution Energy :", energy) print("Solution validty:", valid) global_row = int(math.sqrt(len(G.nodes()))) solution = [] for i in range(1, (global_row**2) + 1): row = [] row.append(sample[i]) print(sample[i] + 1, end=' ') if ((i) % global_row == 0): print("\n") solution.append(row) return valid, solution
def test_DQM_subclass_without_serialization_can_be_sampled(self): """Test that DQM subclasses that do not implement serialization can still be sampled by LeapHybridDQMSampler. Sampling requires serialization. LeapHybridDQMSampler calls DQM.to_file(dqm, ...) if dqm.to_file(...) raises NotImplementedError. """ class DQMWithoutSerialization(dimod.DQM): def to_file(self, *args, **kwargs): raise NotImplementedError class MockSampleset: def relabel_variables(self, *args): return self class MockFuture: sampleset = MockSampleset() class MockSolver: properties = dict(category='hybrid', minimum_time_limit=[[10000, 1.0]]) supported_problem_types = ['dqm'] def sample_dqm(self, *args, **kwargs): return MockFuture() class MockClient: @classmethod def from_config(cls, *args, **kwargs): return cls() def get_solver(self, *args, **kwargs): return MockSolver() with patch('dwave.system.samplers.leap_hybrid_sampler.Client', MockClient): sampler = LeapHybridDQMSampler() dqm = DQMWithoutSerialization() sampler.sample_dqm(dqm)
def test_time_limit_exceptions(self): class MockSolver(): properties = dict( category='hybrid', minimum_time_limit=[[20000, 5.0], [100000, 6.0], [200000, 13.0], [500000, 34.0], [1000000, 71.0], [2000000, 152.0], [5000000, 250.0], [20000000, 400.0], [250000000, 1200.0]], maximum_time_limit_hrs=24.0, ) supported_problem_types = ['dqm'] def sample_dqm(self, *args, **kwargs): raise RuntimeError class MockClient(): @classmethod def from_config(cls, *args, **kwargs): return cls() def get_solver(self, *args, **kwargs): return MockSolver() with patch('dwave.system.samplers.leap_hybrid_sampler.Client', MockClient): sampler = LeapHybridDQMSampler() dqm = dimod.DQM() with self.assertRaises(ValueError): sampler.sample_dqm(dqm, time_limit=1) with self.assertRaises(ValueError): sampler.sample_dqm(dqm, time_limit=10000000)
def test_illegal_edges(self): """Run demo.py and check that no illegal edges are reported. This ensures the lagrange parameter is set appropriately.""" t0 = time.perf_counter() args = demo.read_in_args(["--graph", "internet"]) G = demo.build_graph(args) dqm = demo.build_dqm(G) sampler = LeapHybridDQMSampler() sample = demo.run_dqm_and_collect_solutions(dqm, sampler) group_1, group_2, sep_group, illegal_edges = demo.process_sample(G, sample) self.assertEqual(len(illegal_edges), 0) run_time = time.perf_counter() - t0 print("illegal edges time: ", run_time)
if __name__ == '__main__': passenger_demand, leg_cost, num_cities = read_inputs(flow_file='flow.csv', cost_file='cost.csv') city_names, city_lats, city_longs = read_city_info('city-data.txt') p = 3 # number of hubs a = 0.4 # discount for hub-hub routes # Uncomment lines below to visualize total network options # G = build_graph(passenger_demand, city_names) # draw_graph(G, city_names, city_lats, city_longs) dqm = build_dqm(passenger_demand, leg_cost, num_cities, p, a) print("\nRunning hybrid solver...\n") sampler = LeapHybridDQMSampler() sampleset = sampler.sample_dqm(dqm, label='Example - DQM Airline Hubs') print("\nInterpreting solutions...\n") ss = list(sampleset.data(['sample'])) cost_dict = { index: get_cost(ss[index].sample, a, passenger_demand, leg_cost, num_cities) for index in range(len(ss)) } ordered_samples = dict( sorted(cost_dict.items(), key=lambda item: item[1], reverse=True)) filenames = []
def set_sampler(): '''Returns a dimod sampler''' sampler = LeapHybridDQMSampler() return sampler
lagrange = 10 num_colors = 4 colors = range(num_colors) dqm = DiscreteQuadraticModel() G = nx.Graph() G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (0, 6)]) n_edges = len(G.edges) for p in G.nodes: dqm.add_variable(num_colors, label=p) for p in G.nodes: dqm.set_linear(p, colors) for p0, p1 in G.edges: dqm.set_quadratic(p0, p1, {(c, c): lagrange for c in colors}) for p0, p1 in G.edges: dqm.set_quadratic(p0, p1, {(c, c): lagrange for c in colors}) sampler = LeapHybridDQMSampler() sampleset = sampler.sample_dqm(dqm) sample = sampleset.first.sample energy = sampleset.first.energy valid = True for edge in G.edges: i, j = edge if sample[i] == sample[j]: valid = False break print("Solution: ", sample) print("Solution energy: ", energy) print("Solution validity: ", valid)
for p in G.nodes: linear_term = constraint_const + (0.5 * np.ones(num_partitions) * G.degree[p]) dqm.set_linear(p, linear_term) # Quadratic term for node pairs which do not have edges between them for p0, p1 in nx.non_edges(G): dqm.set_quadratic(p0, p1, {(c, c): (2 * lagrange) for c in partitions}) # Quadratic term for node pairs which have edges between them for p0, p1 in G.edges: dqm.set_quadratic(p0, p1, {(c, c): ((2 * lagrange) - 1) for c in partitions}) # Initialize the DQM solver sampler = LeapHybridDQMSampler() # Solve the problem using the DQM solver offset = lagrange * num_nodes * num_nodes / num_partitions sampleset = sampler.sample_dqm(dqm, label='Example - Graph Partitioning DQM') # get the first solution sample = sampleset.first.sample energy = sampleset.first.energy # Count the nodes in each partition counts = np.zeros(num_partitions) for i in sample: counts[sample[i]] += 1 # Compute the number of links between different partitions
qb_cols = [] qb_biases = [] for i in range(rows * cols): for j in range(i + 1, rows * cols): for case in range(num_segments): qb_rows.append(i * num_segments + case) qb_cols.append(j * num_segments + case) qb_biases.append(weight(i, j, img)) quadratic_biases = (np.asarray(qb_rows), np.asarray(qb_cols), np.asarray(qb_biases)) dqm = DiscreteQuadraticModel.from_numpy_vectors(case_starts, linear_biases, quadratic_biases) # Initialize the DQM solver print("\nRunning DQM solver...") sampler = LeapHybridDQMSampler() # Solve the problem using the DQM solver sampleset = sampler.sample_dqm(dqm, label='Example - Image Segmentation') # Get the first solution sample = sampleset.first.sample print("\nProcessing solution...") im_segmented = np.zeros((rows, cols)) for key, val in sample.items(): x, y = unindexing(key) im_segmented[x, y] = val if random: row_indices = [1 + i for i in range(rows - 1)]
first_letters = set() coefficient_map = defaultdict(int) lhs_list, rhs_list, problem_statement = parse_problem_file(args.filename) update_coefficient_map_and_first_letter_set(lhs_list, 1, coefficient_map, first_letters) update_coefficient_map_and_first_letter_set(rhs_list, -1, coefficient_map, first_letters) variable_list = [] for variable, coefficient in coefficient_map.items(): variable_list.append( LetterVariable(variable, coefficient, first_letter=variable in first_letters)) pprint(variable_list) dqm = build_dqm(variable_list, coefficient_map) # Send DQM to LeapHybridDQMSampler, get response response = LeapHybridDQMSampler().sample_dqm( dqm, time_limit=5, label="Example - Cryptarithmetic").aggregate() lowest_energy_sample = response.first.sample render_solution(lowest_energy_sample, variable_list, lhs_list, rhs_list, problem_statement)
# 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 unittest import dimod import numpy as np from dwave.cloud.exceptions import ConfigFileError, SolverNotFoundError from dwave.system import LeapHybridDQMSampler try: sampler = LeapHybridDQMSampler() except (ValueError, ConfigFileError, SolverNotFoundError): sampler = None @unittest.skipIf(os.getenv('SKIP_INT_TESTS'), "Skipping integration test.") @unittest.skipIf(sampler is None, "no hybrid sampler available") class TestLeapHybridSampler(unittest.TestCase): def test_smoke(self): dqm = dimod.DQM() u = dqm.add_variable(2, 'a') v = dqm.add_variable(3) dqm.set_linear(u, [1, 2]) dqm.set_quadratic(u, v, {(0, 1): 1, (0, 2): 1}) try:
lagrange = max(colors) # Load the DQM. Define the variables, and then set biases and weights. # We set the linear biases to favor lower-numbered colors; this will # have the effect of minimizing the number of colors used. # We penalize edge connections by the Lagrange parameter, to encourage # connected nodes to have different colors. for p in G.nodes: dqm.add_variable(num_colors, label=p) for p in G.nodes: dqm.set_linear(p, colors) for p0, p1 in G.edges: dqm.set_quadratic(p0, p1, {(c, c): lagrange for c in colors}) # Initialize the DQM solver sampler = LeapHybridDQMSampler() # Solve the problem using the DQM solver sampleset = sampler.sample_dqm(dqm, label='Example - Graph Coloring') # get the first solution, and print it sample = sampleset.first.sample energy = sampleset.first.energy # check that colors are different valid = True for edge in G.edges: i, j = edge if sample[i] == sample[j]: valid = False break
# Build the DQM starting by adding variables for name in range(num_employees): dqm.add_variable(num_shifts, label=name) # Distribute employees equally across shifts according to preferences num_per_shift = int(num_employees/num_shifts) gamma = 1/(num_employees*num_shifts) for i in range(num_shifts): for j in range(num_employees): dqm.set_linear_case(j, i, dqm.get_linear_case(j, i) - gamma*(2*num_per_shift+1)) for k in range(j+1, num_employees): dqm.set_quadratic_case(j, i, k, i, gamma*(dqm.get_quadratic_case(j, i, k, i) + 2)) # Initialize the DQM solver sampler = LeapHybridDQMSampler() # Solve the problem using the DQM solver sampleset = sampler.sample_dqm(dqm, label='Example - Employee Scheduling') # Get the first solution, and print it # Mi da la soluzione migliore, quella in cui sono caduto più volte e me la salvo sample = sampleset.first.sample energy = sampleset.first.energy print("\nSchedule score:", energy) # Build schedule schedule = np.ones((num_employees, num_shifts))*num_shifts prefs = [0]*num_shifts shifts = [0]*num_shifts for key, val in sample.items():