コード例 #1
0
    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)
コード例 #2
0
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
コード例 #3
0
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
コード例 #4
0
ファイル: gc_solver.py プロジェクト: adadima/QUBO
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
コード例 #5
0
    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)
コード例 #6
0
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
コード例 #7
0
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
コード例 #8
0
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
コード例 #9
0
ファイル: demo.py プロジェクト: hhtong/airline-hubs
    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 = []
    counter = 0
コード例 #10
0
# 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
sum_diff = 0
for i, j in G.edges:
    if sampleset.first.sample[i] != sampleset.first.sample[j]:
        sum_diff += 1
コード例 #11
0
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)
コード例 #12
0
# 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
print("Solution: ", sample)
print("Solution energy: ", energy)
print("Solution validity: ", valid)
コード例 #13
0
borders = [("BC", "AB"), ("BC", "NT"), ("BC", "YT"), ("AB", "SK"),
           ("AB", "NT"), ("SK", "MB"), ("SK", "NT"), ("MB", "ON"),
           ("MB", "NU"), ("ON", "QU"), ("QU", "NB"), ("QU", "NL"),
           ("NB", "NS"), ("YT", "NT"), ("NT", "NU")]

# input: number of colors in the graph
n_colors = 4
colors = np.linspace(0, n_colors - 1, n_colors)

# Initialize the DQM object
dqm = dimod.DiscreteQuadraticModel()

# Load the DQM. Define the variables, and then set quadratic weights.
# No biases necessary because we don't care what the colors are, as long as
# they are different at the borders.
for p in provinces:
    dqm.add_variable(4, label=p)
for p0, p1 in borders:
    dqm.set_quadratic(p0, p1, {(c, c): 1 for c in colors})

# Initialize the DQM solver
sampler = LeapHybridDQMSampler()

# Solve the problem using the DQM solver
sampleset = sampler.sample_dqm(dqm, label='Example - Map Coloring')

# get the first solution, and print it
sample = sampleset.first.sample
energy = sampleset.first.energy
print(sample, energy)
コード例 #14
0
    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)]
    row_indices.append(0)
    im_segmented_rowwrap = im_segmented[row_indices, :]
コード例 #15
0
ファイル: scheduler.py プロジェクト: RodTol/Tesi
# 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():
    schedule[key,val]=preferences[key,val]
    prefs[preferences[key,val]] += 1
    shifts[val] += 1