示例#1
0
    def test_as_spin(self):
        # add_sample with no energy specified, but Q given

        Q = {(0, 0): -1, (0, 1): 1, (1, 1): -1}

        sample0 = {0: 0, 1: 1}
        sample1 = {0: 1, 1: 1}
        sample2 = {0: 0, 1: 0}

        h, J, offset = qubo_to_ising(Q)

        response = self.response_factory()
        response.add_samples_from([sample0, sample1, sample2], Q=Q)

        response.add_sample(sample0, Q=Q)

        spin_response = response.as_spin(-1 * offset)

        for sample, energy in spin_response.items():
            self.assertEqual(ising_energy(h, J, sample), energy)

        spin_response = response.as_spin(-1 * offset, data_copy=True)
        data_ids = {id(data) for __, data in response.samples(data=True)}
        for __, data in spin_response.samples(data=True):
            self.assertNotIn(id(data), data_ids)
示例#2
0
    def test_as_spin(self):
        response = self.response_factory()

        # set up a BQM and some samples
        Q = {(0, 0): -1, (0, 1): 1, (1, 1): -1}
        h, J, offset = dimod.qubo_to_ising(Q)

        sample0 = {0: 0, 1: 1}
        sample1 = {0: 1, 1: 1}
        sample2 = {0: 0, 1: 0}

        # load up the samples
        response.add_samples_from([sample0, sample1, sample2], Q=Q)
        response.add_sample(sample0, Q=Q)

        # cast to spin
        spin_response = response.as_spin(-offset)

        # check that the energies are correcct
        for sample, energy in spin_response.data(keys=['sample', 'energy']):
            self.assertEqual(dimod.ising_energy(sample, h, J), energy)

        # make a new spin response
        spin_response = response.as_spin(offset)
        data_ids = {id(data) for __, data in response.samples(data=True)}
        for __, data in spin_response.samples(data=True):
            self.assertNotIn(id(data), data_ids)
示例#3
0
def deNovo_on_DWave():
    reads = ['ATGGCGTGCA', 'GCGTGCAATG', 'TGCAATGGCG', 'AATGGCGTGC']
    tspAdjM = reads_to_tspAdjM(reads)
    quboAdjM = tspAdjM_to_quboAdjM(
        tspAdjM, -1.6, 1.6, 1.6)  # self-bias, multi-location, repetation
    quboDict = quboAdjM_to_quboDict(quboAdjM)
    hii, Jij, offset = dimod.qubo_to_ising(quboDict)
    solve_ising_exact(hii, Jij)
    solve_ising_dwave(hii, Jij)
示例#4
0
 def test_typical(self):
     q = {(0, 0): 4, (0, 3): 5, (0, 5): 4, (1, 1): 5, (1, 6): 1, (1, 7): -2,
          (1, 9): -3, (3, 0): -2, (3, 1): 2, (4, 5): 4, (4, 8): 2, (4, 9): -1,
          (5, 1): 2, (5, 6): -5, (5, 8): -4, (6, 0): 1, (6, 5): 2, (6, 6): -4,
          (6, 7): -2, (7, 0): -2, (7, 5): -3, (7, 6): -5, (7, 7): -3, (7, 8): 1,
          (8, 0): 2, (8, 5): 1, (9, 7): -3}
     h, j, offset = qubo_to_ising(q)
     self.assertEqual(h, {0: 4.0, 1: 2.5, 3: 1.25, 4: 1.25, 5: 0.25,
                          6: -4.0, 7: -5.5, 8: 0.5, 9: -1.75})
     norm_j = normalized_matrix(j)
     self.assertEqual(norm_j, {(0, 3): 0.75, (0, 5): 1, (0, 6): 0.25, (0, 7): -0.5,
                               (0, 8): 0.5, (1, 3): 0.5, (1, 5): 0.5, (1, 6): 0.25,
                               (1, 7): -0.5, (1, 9): -0.75, (4, 5): 1, (4, 8): 0.5,
                               (4, 9): -0.25, (5, 6): -0.75, (5, 7): -0.75,
                               (5, 8): -0.75, (6, 7): -1.75, (7, 8): 0.25,
                               (7, 9): -0.75})
     self.assertEqual(offset, -0.25)
示例#5
0
    def test_as_spin(self):
        # add_sample with no energy specified, but Q given

        Q = {(0, 0): -1, (0, 1): 1, (1, 1): -1}

        sample0 = {0: 0, 1: 1}
        sample1 = {0: 1, 1: 1}
        sample2 = {0: 0, 1: 0}

        h, J, offset = qubo_to_ising(Q)

        response = self.response_factory()
        response.add_samples_from([sample0, sample1, sample2], Q=Q)

        spin_response = response.as_spin(-1 * offset)

        for sample, energy in spin_response.items():
            self.assertEqual(ising_energy(h, J, sample), energy)
示例#6
0
    def test_start_from_spin(self):
        Q = {(0, 0): 4, (0, 3): 5, (0, 5): 4, (1, 1): 5, (1, 6): 1, (1, 7): -2,
             (1, 9): -3, (3, 0): -2, (3, 1): 2, (4, 5): 4, (4, 8): 2, (4, 9): -1,
             (5, 1): 2, (5, 6): -5, (5, 8): -4, (6, 0): 1, (6, 5): 2, (6, 6): -4,
             (6, 7): -2, (7, 0): -2, (7, 5): -3, (7, 6): -5, (7, 7): -3, (7, 8): 1,
             (8, 0): 2, (8, 5): 1, (9, 7): -3}
        qoff = 1.3

        h, J, ioff = qubo_to_ising(Q, qoff)

        bin_sample = {}
        ising_sample = {}
        for v in h:
            bin_sample[v] = 0
            ising_sample[v] = -1

        self.assertAlmostEqual(ising_energy(ising_sample, h, J, ioff),
                               qubo_energy(bin_sample, Q, qoff))
示例#7
0
    def test_as_spin_array(self):
        response = self.response_factory()

        # set up a BQM and some samples
        Q = {(0, 0): -1, (0, 1): 1, (1, 1): -1}
        h, J, offset = dimod.qubo_to_ising(Q)

        samples = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 0], [1, 1, 1]], dtype=int)
        energies = np.array([dimod.qubo_energy(row, Q) for row in samples])
        response.add_samples_from_array(samples, energies)

        # cast to spin
        spin_response = response.as_spin(-offset)

        # check that the energies are correcct
        for sample, energy in spin_response.items():
            self.assertEqual(dimod.ising_energy(sample, h, J), energy)

        # make a new spin response
        spin_response = response.as_spin(offset)
        data_ids = {id(data) for __, data in response.samples(data=True)}
        for __, data in spin_response.samples(data=True):
            self.assertNotIn(id(data), data_ids)
示例#8
0
def anneal(C_i, C_ij, mu, sigma, l, strength_scale, energy_fraction, ngauges,
           max_excited_states):
    #Initialising h and J as dictionnaries
    h = {}
    J = {}

    for i in range(len(C_i)):
        h_i = -2 * sigma[i] * C_i[i]
        for j in range(len(C_ij[0])):
            if j > i:
                J[(i, j)] = float(2 * C_ij[i][j] * sigma[i] * sigma[j])
            h_i += 2 * (sigma[i] * C_ij[i][j] * mu[j])
        h[i] = h_i

    #applying cutoff
    print("Number of J before : " + str(len(J)))  #J before cutoff
    float_vals = []
    for i in J.values():
        float_vals.append(i)
    cutoff = np.percentile(float_vals, AUGMENT_CUTOFF_PERCENTILE)
    to_delete = []
    for k, v in J.items():
        if v < cutoff:
            to_delete.append(k)
    for k in to_delete:
        del J[k]
    print("Number of J after : " + str(len(J)))  # J after cutof
    new_Q = {}
    isingpartial = {}

    if FIXING_VARIABLES:
        #Optimising heuristically the number of coupling terms
        Q, _ = dimod.ising_to_qubo(h, J, offset=0.0)
        bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=0.0)
        simple = dimod.fix_variables(bqm, sampling_mode=False)
        if simple == {}:
            new_Q = Q
        else:
            Q_indices = []
            for i in Q:
                if i in simple.keys():
                    continue
                else:
                    Q_indices.append(i)
            new_Q = {key: Q[key] for key in Q_indices}
        print('new length', len(new_Q))
        isingpartial = simple

    if (not FIXING_VARIABLES) or len(new_Q) > 0:
        mapping = []
        offset = 0
        for i in range(len(C_i)):
            if i in isingpartial:
                mapping.append(None)
                offset += 1
            else:
                mapping.append(i - offset)
        if FIXING_VARIABLES:
            new_Q_mapped = {}
            for (first, second), val in new_Q.items():
                new_Q_mapped[(mapping[first], mapping[second])] = val
            h, J, _ = dimod.qubo_to_ising(new_Q_mapped)

        #Run gauges
        qaresults = []
        print("Number of variables to anneal :" + str(len(h)))
        for g in range(ngauges):
            #Finding embedding
            qaresult = []
            embedded = False
            for attempt in range(5):
                a = np.sign(np.random.rand(len(h)) - 0.5)
                float_h = []
                for i in h.values():
                    float_h.append(i)
                h_gauge = float_h * a
                J_gauge = {}
                for i in range(len(h)):
                    for j in range(len(h)):
                        if (i, j) in J:
                            J_gauge[(i, j)] = J[(i, j)] * a[i] * a[j]
                try:
                    print("Trying to find embeding")
                    sampler = EmbeddingComposite(
                        DWaveSampler(token='secret_token'))
                    embedded = True
                    break
                except ValueError:  # no embedding found
                    print('no embedding found')
                    embedded = False
                    continue

            if not embedded:
                continue
            print("emebeding found")

            print("Quantum annealing")
            try_again = True
            while try_again:
                try:
                    #Annealing, saving energy and sample list
                    sampleset = sampler.sample_ising(
                        h_gauge,
                        J_gauge,
                        chain_strength=strength_scale,
                        num_reads=200,
                        annealing_time=20)
                    try_again = False
                except:
                    print('runtime or ioerror, trying again')
                    time.sleep(10)
                    try_again = True
            print("Quantum done")

            qaresult.append(sampleset.record[0][0].tolist())
            qaresult = np.asarray(qaresult)
            qaresult = qaresult * a
            qaresults[g * nreads:(g + 1) * nreads] = qaresult

        full_strings = np.zeros((len(qaresults), len(C_i)))
        full_strings = np.asarray(full_strings)
        qaresults = np.asarray(qaresults)
        if FIXING_VARIABLES:
            j = 0
            for i in range(len(C_i)):
                if i in isingpartial:
                    full_strings[:, i] = 2 * isingpartial[i] - 1
                else:
                    full_strings[:, i] = qaresults[:, j]
                    j += 1
        else:
            full_strings = qaresults

        s = np.asarray(full_strings)
        energies = np.zeros(len(qaresults))
        s[np.where(s > 1)] = 1.0
        s[np.where(s < -1)] = -1.0
        bits = len(s[0])
        for i in range(bits):
            energies += 2 * s[:, i] * (-sigma[i] * C_i[i])
            for j in range(bits):
                if j > i:
                    energies += 2 * s[:, i] * s[:, j] * sigma[i] * sigma[
                        j] * C_ij[i][j]
                energies += 2 * s[:, i] * sigma[i] * C_ij[i][j] * mu[j]

        unique_energies, unique_indices = np.unique(energies,
                                                    return_index=True)
        ground_energy = np.amin(unique_energies)
        if ground_energy < 0:
            threshold_energy = (1 - energy_fraction) * ground_energy
        else:
            threshold_energy = (1 + energy_fraction) * ground_energy
        lowest = np.where(unique_energies < threshold_energy)
        unique_indices = unique_indices[lowest]
        if len(unique_indices) > max_excited_states:
            sorted_indices = np.argsort(
                energies[unique_indices])[-max_excited_states:]
            unique_indices = unique_indices[sorted_indices]
        print("unique indices : ", unique_indices)
        print(type(unique_indices[0]))
        print(type(full_strings))
        final_answers = full_strings[unique_indices]
        print('number of selected excited states', len(final_answers))

        return final_answers

    else:
        final_answer = []
        print("Evrything resolved by FIXING_VARIABLES")
        for i in range(len(C_i)):
            if i in isingpartial:
                final_answer.append(2 * isingpartial[i] - 1)
        final_answer = np.array(final_answer)
        return np.array([final_answer])
示例#9
0
 def test_no_zeros(self):
     h, j, offset = qubo_to_ising({(0, 0): 0, (4, 5): 0})
     self.assertEqual(h, {0: 0, 4: 0, 5: 0})
     self.assertEqual(j, {})
     self.assertEqual(offset, 0)
示例#10
0
 def test_trivial(self):
     h, j, offset = qubo_to_ising({})
     self.assertEqual(h, {})
     self.assertEqual(j, {})
     self.assertEqual(offset, 0)
示例#11
0
Q = {}
for i in range(0, 16):
    ni = 'n' + str(int(i / 4)) + 't' + str(int(i % 4))
    for j in range(0, 16):
        nj = 'n' + str(int(j / 4)) + 't' + str(int(j % 4))
        if Q_matrix[i][j] != 0:
            Q[(ni, nj)] = Q_matrix[i][j]

response = solver.sample_qubo(Q)

minE = min(response.data(['sample', 'energy']), key=lambda x: x[1])
for sample, energy in response.data(['sample', 'energy']):
    if energy == minE[1]:
        print(sample)

hii, Jij, offset = dimod.qubo_to_ising(Q)

response = solver.sample_ising(hii, Jij)

print()
minE = min(response.data(['sample', 'energy']), key=lambda x: x[1])
for sample, energy in response.data(['sample', 'energy']):
    if energy == minE[1]:
        print(sample)

import matplotlib.pyplot as plt
y = []
for sample, energy in response.data(['sample', 'energy']):
    y.append(energy)
plt.plot(y)
plt.xlabel('Solution landscape')
示例#12
0
    return y


print('accuracy (train): %5.2f' %
      (metric(y_train, predict(models, weights, X_train))))
print('accuracy (test): %5.2f' %
      (metric(y_test, predict(models, weights, X_test))))

# Accuracy co-incides with strongest weak learners, AdaBoost.

print('QAOA -----------------------------')
# Solve with QAOA

# Map the QUBO to a Ising model
h, J, offset = dimod.qubo_to_ising(W)

from pyquil import Program, api
from pyquil.paulis import PauliSum, PauliTerm
from scipy.optimize import fmin_bfgs
from grove.pyqaoa.qaoa import QAOA
from forest_tools import *
qvm = api.SyncConnection()

num_nodes = w.shape[0]
ising_model = []
for i in range(num_nodes):
    ising_model.append(PauliSum([PauliTerm("Z", i, h[i])]))
    for j in range(i + 1, num_nodes):
        ising_model.append(
            PauliSum([PauliTerm("Z", i, J[i, j]) * PauliTerm("Z", j, 1.0)]))