Esempio n. 1
0
    def test_full_yield_one_tile_k3(self):
        emb = find_clique_embedding(3, 1)

        target = dnx.chimera_graph(1)

        source = dimod.embedding.target_to_source(target, emb)

        self.assertEqual(source, {0: {1, 2}, 1: {0, 2}, 2: {0, 1}})
    def test_full_yield_one_tile_k2(self):
        emb = find_clique_embedding(2, 1)

        target = dnx.chimera_graph(1)

        source = dwave.embedding.target_to_source(target, emb)

        self.assertEqual(source, {0: {1}, 1: {0}})
Esempio n. 3
0
    def dwave_physical_DW_2000Q_5(self):
        print("\nD-wave quantum annealer....")
        from dwave.system import DWaveSampler, FixedEmbeddingComposite
        from dwave.embedding.chimera import find_clique_embedding

        qpu = DWaveSampler(token=self.token,
                           endpoint=self.endpoint,
                           solver=dict(name='DW_2000Q_5'),
                           auto_scale=False)
        self.title = "D-Wave Quantum Annealer"

        embedding = find_clique_embedding(
            self.bqm.variables,
            16,
            16,
            4,  # size of the chimera lattice
            target_edges=qpu.edgelist)

        qpu_sampler = FixedEmbeddingComposite(qpu, embedding)

        print("Maximum chain length for minor embedding is {}.".format(
            max(len(x) for x in embedding.values())))

        from hybrid.reference.kerberos import KerberosSampler
        kerberos_sampler = KerberosSampler()

        selected_features = np.zeros((len(self.features), len(self.features)))
        for k in range(1, len(self.features) + 1):
            print("Submitting for k={}".format(k))
            kbqm = dimod.generators.combinations(self.features, k, strength=6)
            kbqm.update(self.bqm)
            kbqm.normalize()

            best = kerberos_sampler.sample(kbqm,
                                           qpu_sampler=qpu_sampler,
                                           num_reads=10,
                                           max_iter=1).first.sample

            for fi, f in enumerate(self.features):
                selected_features[k - 1, fi] = best[f]
        if self.is_notebook:
            from helpers.draw import plot_feature_selection
            plot_feature_selection(self.features, selected_features)
    def test_str_labels(self):
        emb = find_clique_embedding(['a', 'b'], 1)

        self.assertEqual(len(emb), 2)
        self.assertIn('a', emb)
        self.assertIn('b', emb)
    def test_k2_to_single_chimera_edge(self):
        emb = find_clique_embedding(2, 1, target_edges=[(0, 4)])

        self.assertDictEqual({0: [0], 1: [4]}, emb)
    def test_k1(self):
        emb = find_clique_embedding(1, 1)

        self.assertSetEqual({0}, set(emb.keys()))
        self.assertLessEqual(set(emb[0]), set(range(8)))
def run_demo():
    # Read the feature-engineered data into a pandas dataframe
    # Data obtained from http://biostat.mc.vanderbilt.edu/DataSets
    demo_path = os.path.dirname(os.path.abspath(__file__))
    data_path = os.path.join(demo_path, 'data', 'formatted_titanic.csv')
    dataset = pd.read_csv(data_path)

    # Rank the MI between survival and every other variable
    scores = {}
    features = list(set(dataset.columns).difference(('survived', )))
    for feature in features:
        scores[feature] = mutual_information(
            prob(dataset[['survived', feature]].values), 0)

    labels, values = zip(
        *sorted(scores.items(), key=lambda pair: pair[1], reverse=True))

    # Plot the MI between survival and every other variable
    plt.figure()
    ax1 = plt.subplot(1, 2, 1)
    ax1.set_title("Mutual Information")
    ax1.set_ylabel('MI Between Survival and Feature')
    plt.xticks(np.arange(len(labels)), labels, rotation=90)
    plt.bar(np.arange(len(labels)), values)

    # The Titanic dataset provides a familiar, intuitive example available in the public
    # domain. In itself, however, it is not a good fit for solving by sampling. Run naively on
    # this dataset, it finds numerous good solutions but is unlikely to find the exact optimal solution.
    # There are many techniques for reformulating problems for the D-Wave system that can
    # improve performance on various metrics, some of which can help narrow down good solutions
    # to closer approach an optimal solution.
    # This demo solves the problem for just the highest-scoring features.

    # Select 8 features with the top MI ranking found above.
    keep = 8

    sorted_scores = sorted(scores.items(),
                           key=lambda pair: pair[1],
                           reverse=True)
    dataset = dataset[[column[0]
                       for column in sorted_scores[0:keep]] + ["survived"]]
    features = list(set(dataset.columns).difference(('survived', )))

    # Build a QUBO that maximizes MI between survival and a subset of features
    bqm = dimod.BinaryQuadraticModel.empty(dimod.BINARY)

    # Add biases as (negative) MI with survival for each feature
    for feature in features:
        mi = mutual_information(prob(dataset[['survived', feature]].values), 1)
        bqm.add_variable(feature, -mi)

    # Add interactions as (negative) MI with survival for each set of 2 features
    for f0, f1 in itertools.combinations(features, 2):
        cmi_01 = conditional_mutual_information(
            prob(dataset[['survived', f0, f1]].values), 1, 2)
        cmi_10 = conditional_mutual_information(
            prob(dataset[['survived', f1, f0]].values), 1, 2)
        bqm.add_interaction(f0, f1, -cmi_01)
        bqm.add_interaction(f1, f0, -cmi_10)

    bqm.normalize()  # Normalize biases & interactions to the range -1, 1

    # Set up a QPU sampler with a fully-connected graph of all the variables
    qpu_sampler = DWaveSampler(solver={'qpu': True})

    embedding = find_clique_embedding(
        bqm.variables,
        16,
        16,
        4,  # size of the chimera lattice
        target_edges=qpu_sampler.edgelist)

    sampler = FixedEmbeddingComposite(qpu_sampler, embedding)

    # For each number of features, k, penalize selection of fewer or more features
    selected_features = np.zeros((len(features), len(features)))
    for k in range(1, len(features) + 1):
        kbqm = bqm.copy()
        kbqm.update(dimod.generators.combinations(
            features, k, strength=6))  # Determines the penalty

        sample = sampler.sample(kbqm, num_reads=10000).first.sample

        for fi, f in enumerate(features):
            selected_features[k - 1, fi] = sample[f]

    # Plot the best feature set per number of selected features
    ax2 = plt.subplot(1, 2, 2)
    ax2.set_title("Best Feature Selection")
    ax2.set_ylabel('Number of Selected Features')
    ax2.set_xticks(np.arange(len(features)))
    ax2.set_xticklabels(features, rotation=90)
    ax2.set_yticks(np.arange(len(features)))
    ax2.set_yticklabels(np.arange(1, len(features) + 1))
    # Set a grid on minor ticks
    ax2.set_xticks(np.arange(-0.5, len(features)), minor=True)
    ax2.set_yticks(np.arange(-0.5, len(features)), minor=True)
    ax2.grid(which='minor', color='black')
    ax2.imshow(selected_features, cmap=colors.ListedColormap(['white', 'red']))

    plots_path = os.path.join(demo_path, "plots.png")
    plt.savefig(plots_path, bbox_inches="tight")
    print("Your plots are saved to {}".format(plots_path))
Esempio n. 8
0
Q, offset = model.to_qubo()
bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=offset)

# Need to relabel variables for the first figure
bqm2 = bqm.relabel_variables({curr: v
                              for v, curr in enumerate(bqm.variables)},
                             inplace=False)

# Do the embedding
dwave_sampler = DWaveSampler()
A = dwave_sampler.edgelist
embedding = find_embedding(Q, A)

# Draw the QUBO as a networkx graph
G = bqm2.to_networkx_graph()
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos, font_size=10, node_size=150)
plt.show()

# Draw the embedded graph
G = dnx.chimera_graph(16, 16, 4)
dnx.draw_chimera_embedding(G,
                           embedding,
                           embedded_graph=bqm.to_networkx_graph(),
                           unused_color=None)
plt.show()

clique_embedding = find_clique_embedding(N, 16, 16, 4, A)
dnx.draw_chimera_embedding(G, clique_embedding, unused_color=None)
plt.show()