Ejemplo n.º 1
0
import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt

# Importo l'analizzatore
import dwave.inspector

# Selezioni il sampler che useremo. Voglio un metodo quantistico,
# quindi uso il DwaweSampler
from dwave.system.samplers import DWaveSampler

# Utilizzo un composite per fare l'embedding
from dwave.system.composites import EmbeddingComposite

# Preparo il sampler usando l'embedding scelto
sampler = EmbeddingComposite(DWaveSampler(solver='Advantage_system1.1'))

# Creo un grafo vuoto
G = nx.Graph()

# Prendo un grafo da un file
grafo = open(
    "/workspace/Tesi/Esempi-commentati/Pipelines-Antennas/JOHNSON8-2-4.txt",
    "rb")
#grafo = open("/workspace/Tesi/Esempi-commentati/Pipelines-Antennas/chesapeake.txt", "rb")
G = nx.read_edgelist(grafo)


#Creo la funzione per formulare il QUBO
def massimo_set_indipendente_qubo(G, weight=None, lagrange=2.0):
    # un QUBO vuoto per un grafo vuoto
Ejemplo n.º 2
0
# -*- coding: utf-8 -*-
"""
Created on Thu Jun  4 16:49:59 2020

@author: usama
"""

from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
import matplotlib.pyplot as plt
import neal
import numpy as np
from numpy.random import randn

token = 'Enter Dwave Token'
sampler = EmbeddingComposite(DWaveSampler(token=token, solver={'qpu': True}))

#sampler=neal.SimulatedAnnealingSampler()


#This function is taken from Dr Fayyaz ul Amir Afsar Minhas (Github User: foxtrotmike)
def getExamples(n=100, d=2):
    """
    Generates n d-dimensional normally distributed examples of each class        
    The mean of the positive class is [1] and for the negative class it is [-1]
    DO NOT CHANGE THIS FUNCTION
    """
    Xp = randn(n, d) + 1  #generate n examples of the positive class
    #Xp[:,0]=Xp[:,0]+1
    Xn = randn(n, d) - 1  #generate n examples of the negative class
    #Xn[:,0]=Xn[:,0]-1
Ejemplo n.º 3
0
    def setUp(self, MockClient):

        # using the mock
        self.sampler = DWaveSampler()

        self.sampler.solver = MockSolver()
Ejemplo n.º 4
0
fixed_variables = dict(zip(reversed(p_vars), "{:06b}".format(P)))
fixed_variables = {var: int(x) for (var, x) in fixed_variables.items()}

## Fix the result of the product (kind of making a constrain).
## As a resul all 'p0',...,'p5' will be removed from the bqm.
for var, value in fixed_variables.items():
    bqm.fix_variable(var, value)

## SETTING UP A SOLVER

from helpers.solvers import default_solver
#my_solver, my_token = default_solver()

from dwave.system.samplers import DWaveSampler
#sampler = DWaveSampler(solver={'qpu': True})  # Some accounts need to replace this line with the next:
sampler = DWaveSampler(solver={'qpu': True},
                       token='DEV-7201bbe105379663905954b7ed302eed2bd97866')
_, target_edgelist, target_adjacency = sampler.structure

## embedding
from dwave.embedding import embed_bqm, unembed_sampleset
from helpers.embedding import embeddings

## Embedding logical qubits to physical ones
embedding = embeddings[sampler.solver.id]

## Set connections betweeen physical qubits
bqm_embedded = embed_bqm(bqm, embedding, target_adjacency, 4.0)
#print(bqm_embedded)

# Return num_reads solutions (responses are in the D-Wave's graph of indexed qubits)
kwargs = {}
import networkx as nx
import dwave_networkx as dnx
from minorminer import find_embedding
from dwave.system.samplers import DWaveSampler

try:
    import matplotlib.pyplot as plt
except ImportError:
    matplotlib.use("agg")
    import matplotlib.pyplot as plt

N = int(sys.argv[1])
G = nx.complete_graph(N)

# Do the embedding
dwave_sampler = DWaveSampler(solver={'topology__type__eq': 'chimera'})
A = dwave_sampler.edgelist
embedding = find_embedding(G, A)

qubits = 0
for chain in embedding.values():
    qubits += len(chain)

print("\nEmbedding for", N, "clique found using", qubits, "qubits.")

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 6))
node_color_list = [(random(), random(), random()) for i in range(N)]
chain_color_list = {i: node_color_list[i] for i in range(N)}

# Draw the QUBO as a networkx graph
pos = nx.spring_layout(G)
Ejemplo n.º 6
0
        location = 'office' if sample['location'] else 'home'
        length = 'short' if sample['length'] else 'long'
        mandatory = 'mandatory' if sample['mandatory'] else 'optional'
        print(
            "During {} at {}, you can schedule a {} meeting that is {}".format(
                time, location, length, mandatory))

print(
    '################################################################################'
)

# Solving on a D-Wave System
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
sampler = EmbeddingComposite(
    DWaveSampler()
)  # endpoint='https://URL_to_my_D-Wave_system/', token='ABC-123456789012345678901234567890', solver='My_D-Wave_Solver'
response = sampler.sample(
    bqm, num_reads=50
)  # map our unstructured problem (variables such as time etc.) to the sampler's graph structure (the QPU's numerically indexed qubits) in a process known as minor-embedding.

total = 0
for sample, energy, occurrences in response.data(
    ['sample', 'energy', 'num_occurrences'], sorted_by='num_occurrences'):
    total = total + occurrences
    if energy == min_energy:  # prints all those solutions (assignments of variables) for which the BQM has its minimum value and the number of times it was found
        time = 'business hours' if sample['time'] else 'evenings'
        location = 'office' if sample['location'] else 'home'
        length = 'short' if sample['length'] else 'long'
        mandatory = 'mandatory' if sample['mandatory'] else 'optional'
        print("{}: During {} at {}, you can schedule a {} meeting that is {}".
Ejemplo n.º 7
0
def train_model(X_train, y_train, X_test, y_test, lmd):
    """
    Train qboost model

    :param X_train: train input
    :param y_train: train label
    :param X_test: test input
    :param y_test: test label
    :param lmd: lmbda to control regularization term
    :return:
    """
    NUM_READS = 3000
    NUM_WEAK_CLASSIFIERS = 35
    # lmd = 0.5
    TREE_DEPTH = 3

    # define sampler
    dwave_sampler = DWaveSampler(solver={'qpu': True})
    # sa_sampler = micro.dimod.SimulatedAnnealingSampler()
    emb_sampler = EmbeddingComposite(dwave_sampler)

    N_train = len(X_train)
    N_test = len(X_test)

    print("\n======================================")
    print("Train#: %d, Test: %d" % (N_train, N_test))
    print('Num weak classifiers:', NUM_WEAK_CLASSIFIERS)
    print('Tree depth:', TREE_DEPTH)

    # input: dataset X and labels y (in {+1, -1}

    # Preprocessing data
    imputer = SimpleImputer()
    # scaler = preprocessing.MinMaxScaler()
    scaler = preprocessing.StandardScaler()
    normalizer = preprocessing.Normalizer()
    centerer = preprocessing.KernelCenterer()

    # X = imputer.fit_transform(X)
    X_train = scaler.fit_transform(X_train)
    X_train = normalizer.fit_transform(X_train)
    X_train = centerer.fit_transform(X_train)

    # X_test = imputer.fit_transform(X_test)
    X_test = scaler.fit_transform(X_test)
    X_test = normalizer.fit_transform(X_test)
    X_test = centerer.fit_transform(X_test)

    ## Adaboost
    print('\nAdaboost')

    clf = AdaBoostClassifier(n_estimators=NUM_WEAK_CLASSIFIERS)

    # scores = cross_val_score(clf, X, y, cv=5, scoring='accuracy')
    print('fitting...')
    clf.fit(X_train, y_train)

    hypotheses_ada = clf.estimators_
    # clf.estimator_weights_ = np.random.uniform(0,1,size=NUM_WEAK_CLASSIFIERS)
    print('testing...')
    y_train_pred = clf.predict(X_train)
    y_test_pred = clf.predict(X_test)

    print('accu (train): %5.2f' % (metric(y_train, y_train_pred)))
    print('accu (test): %5.2f' % (metric(y_test, y_test_pred)))

    # Ensembles of Decision Tree
    print('\nDecision tree')

    clf2 = WeakClassifiers(n_estimators=NUM_WEAK_CLASSIFIERS,
                           max_depth=TREE_DEPTH)
    clf2.fit(X_train, y_train)

    y_train_pred2 = clf2.predict(X_train)
    y_test_pred2 = clf2.predict(X_test)
    print(clf2.estimator_weights)

    print('accu (train): %5.2f' % (metric(y_train, y_train_pred2)))
    print('accu (test): %5.2f' % (metric(y_test, y_test_pred2)))

    # Ensembles of Decision Tree
    print('\nQBoost')

    DW_PARAMS = {
        'num_reads': NUM_READS,
        'auto_scale': True,
        # "answer_mode": "histogram",
        'num_spin_reversal_transforms': 10,
        # 'annealing_time': 10,
        'postprocess': 'optimization',
    }

    clf3 = QBoostClassifier(n_estimators=NUM_WEAK_CLASSIFIERS,
                            max_depth=TREE_DEPTH)
    clf3.fit(X_train, y_train, emb_sampler, lmd=lmd, **DW_PARAMS)

    y_train_dw = clf3.predict(X_train)
    y_test_dw = clf3.predict(X_test)

    print(clf3.estimator_weights)

    print('accu (train): %5.2f' % (metric(y_train, y_train_dw)))
    print('accu (test): %5.2f' % (metric(y_test, y_test_dw)))

    # Ensembles of Decision Tree
    print('\nQBoostPlus')
    clf4 = QboostPlus([clf, clf2, clf3])
    clf4.fit(X_train, y_train, emb_sampler, lmd=lmd, **DW_PARAMS)
    y_train4 = clf4.predict(X_train)
    y_test4 = clf4.predict(X_test)
    print(clf4.estimator_weights)

    print('accu (train): %5.2f' % (metric(y_train, y_train4)))
    print('accu (test): %5.2f' % (metric(y_test, y_test4)))

    print("=============================================")
    print("Method \t Adaboost \t DecisionTree \t Qboost \t QboostIt")
    print("Train\t %5.2f \t\t %5.2f \t\t\t %5.2f \t\t %5.2f" %
          (metric(y_train, y_train_pred), metric(y_train, y_train_pred2),
           metric(y_train, y_train_dw), metric(y_train, y_train4)))
    print("Test\t %5.2f \t\t %5.2f \t\t\t %5.2f \t\t %5.2f" %
          (metric(y_test, y_test_pred), metric(y_test, y_test_pred2),
           metric(y_test, y_test_dw), metric(y_test, y_test4)))
    print("=============================================")

    # plt.subplot(211)
    # plt.bar(range(len(y_test)), y_test)
    # plt.subplot(212)
    # plt.bar(range(len(y_test)), y_test_dw)
    # plt.show()

    return
Ejemplo n.º 8
0
def factor(P, use_saved_embedding=True):

    ####################################################################################################
    # get circuit
    ####################################################################################################

    construction_start_time = time.time()

    validate_input(P, range(2 ** 6))

    # get constraint satisfaction problem
    csp = dbc.factories.multiplication_circuit(3)

    # get binary quadratic model
    bqm = dbc.stitch(csp, min_classical_gap=.1)

    # we know that multiplication_circuit() has created these variables
    p_vars = ['p0', 'p1', 'p2', 'p3', 'p4', 'p5']

    # convert P from decimal to binary
    fixed_variables = dict(zip(reversed(p_vars), "{:06b}".format(P)))
    fixed_variables = {var: int(x) for(var, x) in fixed_variables.items()}

    # fix product qubits
    for var, value in fixed_variables.items():
        bqm.fix_variable(var, value)

    log.debug('bqm construction time: %s', time.time() - construction_start_time)

    ####################################################################################################
    # run problem
    ####################################################################################################

    sample_time = time.time()

    # get QPU sampler
    sampler = DWaveSampler()
    _, target_edgelist, target_adjacency = sampler.structure

    if use_saved_embedding:
        # load a pre-calculated embedding
        from factoring.embedding import embeddings
        embedding = embeddings[sampler.solver.id]
    else:
        # get the embedding
        embedding = minorminer.find_embedding(bqm.quadratic, target_edgelist)
        if bqm and not embedding:
            raise ValueError("no embedding found")

    # apply the embedding to the given problem to map it to the sampler
    bqm_embedded = dimod.embed_bqm(bqm, embedding, target_adjacency, 3.0)

    # draw samples from the QPU
    kwargs = {}
    if 'num_reads' in sampler.parameters:
        kwargs['num_reads'] = 50
    if 'answer_mode' in sampler.parameters:
        kwargs['answer_mode'] = 'histogram'
    response = sampler.sample(bqm_embedded, **kwargs)

    # convert back to the original problem space
    response = dimod.unembed_response(response, embedding, source_bqm=bqm)

    sampler.client.close()

    log.debug('embedding and sampling time: %s', time.time() - sample_time)

    ####################################################################################################
    # output results
    ####################################################################################################

    output = {
        "results": [],
        #    {
        #        "a": Number,
        #        "b": Number,
        #        "valid": Boolean,
        #        "numOfOccurrences": Number,
        #        "percentageOfOccurrences": Number
        #    }
        "timing": {
            "actual": {
                "qpuProcessTime": None  # microseconds
            }
        },
        "numberOfReads": None
    }

    # we know that multiplication_circuit() has created these variables
    a_vars = ['a0', 'a1', 'a2']
    b_vars = ['b0', 'b1', 'b2']

    # histogram answer_mode should return counts for unique solutions
    if 'num_occurrences' not in response.data_vectors:
        response.data_vectors['num_occurrences'] = [1] * len(response)

    # should equal num_reads
    total = sum(response.data_vectors['num_occurrences'])

    results_dict = OrderedDict()
    for sample, num_occurrences in response.data(['sample', 'num_occurrences']):
        # convert A and B from binary to decimal
        a = b = 0
        for lbl in reversed(a_vars):
            a = (a << 1) | sample[lbl]
        for lbl in reversed(b_vars):
            b = (b << 1) | sample[lbl]
        # aggregate results by unique A and B values (ignoring internal circuit variables)
        if (a, b, P) in results_dict:
            results_dict[(a, b, P)]["numOfOccurrences"] += num_occurrences
            results_dict[(a, b, P)]["percentageOfOccurrences"] = 100 * \
                results_dict[(a, b, P)]["numOfOccurrences"] / total
        else:
            results_dict[(a, b, P)] = {"a": a,
                                       "b": b,
                                       "valid": a * b == P,
                                       "numOfOccurrences": num_occurrences,
                                       "percentageOfOccurrences": 100 * num_occurrences / total}

    output['results'] = list(results_dict.values())
    output['numberOfReads'] = total
    if 'timing' in response.info:
        output['timing']['actual']['qpuProcessTime'] = response.info['timing']['qpu_access_time']

    return output
# q_0 + q_4 - 2 q_0 q_4 - 1
#
# Constrain qubits 1 and 4 to have opposite values - but notice that we're
# going to embed qubits 1 and 5 to have the same value
# 2 q_1 q_4 - q_4 - 0.5 (q_1 + q_5)
#
# Constrain qubits 0 and 5 to have the same value - and yes, we will embed
# 1 and 5 to have the same value
# q_0 + 0.5 (q_1 + q_5) - 2 q_0 q_5 - 1
#
# Constrain qubits 1 and 5 to have the same value, explicitly
# chainstrength (q_1 + q_5 - 2q_1 q_5 - 1)

numruns = 1000
chainstrength = float(sys.argv[1])
sampler = DWaveSampler(solver={'topology__type': 'chimera'})

# Add all the equations together
Q = {
    (0, 0): 2,
    (1, 1): chainstrength,
    (5, 5): chainstrength,
    (0, 4): -2,
    (1, 4): 2,
    (0, 5): -2,
    (1, 5): -2 * chainstrength
}

bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=-2 - chainstrength)

results = sampler.sample(bqm, num_reads=numruns)
Ejemplo n.º 10
0
qdict = prb.get_cvrptw_qubo(penalty_const, reward_const, capacity_const,
                            time_windows_const).dict
printqubo = False
if printqubo:
    for key in qdict.keys():
        ((v, d, t), (v2, d2, t2)) = key
        # if qdict[key] < penalty_const and abs(qdict[(key)]) > 0.1:
        if (v == v2) and (d == d2) and (d != 0) and (t != t2):
            print(key, end='')
            print(" - ", end='')
            print(qdict[key])

print("annealing")

solver = hybrid_solver()
# solver = neal.SimulatedAnnealingSampler()
dwave_sampler = DWaveSampler(token=DWAVE_API_TOKEN, endpoint=endpoint)
response = solver.sample_qubo(qdict)

for sample in response:
    # for key in sample:
    # if sample[key] == 1:
    # print(key)

    solution = CVRPTWSolution(prb, sample)
    solution.description()
    # print(solution.total_cost())
    print(solution.check())
    print('energy: ', energy(qdict, sample, False))
    print()
Ejemplo n.º 11
0
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License 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.

from dwave.system.samplers import DWaveSampler
from dwave.system.composites import LazyFixedEmbeddingComposite
import sys
import dimod

# Set up the QUBO. Start with the equations from the slides:
chainstrength = float(sys.argv[1])
numruns = 1000
Q = {(0, 0): 2, (0, 1): -2, (0, 2): -2, (1, 2): 2}
bqm = dimod.BinaryQuadraticModel.from_qubo(Q, offset=-2)

sampler = LazyFixedEmbeddingComposite(
    DWaveSampler(solver={'topology__type': 'pegasus'}))
response = sampler.sample(bqm, chain_strength=chainstrength, num_reads=numruns)
print(sampler.properties['embedding'])

for sample, energy in response.data(['sample', 'energy']):
    print(sample, energy)
Ejemplo n.º 12
0
def solve(d_min, eta, i_max, k, lambda_zero, n, N, N_max, p_delta, q, topology,
          Q, DIR, sim):
    try:
        if (not sim):
            string = "\n---------- Started Algorithm in Quantum Mode ----------\n"
            print(string)
            write(DIR, string)
            sampler = DWaveSampler(solver={
                'topology__type': topology,
                'qpu': True,
                'annealing_time': 0.001
            })
            A = get_active(sampler, n)
        else:
            string = "\n---------- Started Algorithm in Simulating Mode ----------"
            print(string)
            write(DIR, string)
            sampler = neal.SimulatedAnnealingSampler()

            if (topology == 'chimera'):
                string = "----------        Using Chimera Topology        ----------\n"
                print(string)
                write(DIR, string)
                if (n > 2048):
                    n = int(
                        input(
                            f"WARNING: {n} inserted value is bigger than max topology size (2048), please insert a valid n or press any key to exit: "
                        ))
                try:
                    A = generate_chimera(n)
                except:
                    exit()
            else:
                string = "----------        Using Pegasus Topology        ----------\n"
                print(string)
                write(DIR, string)
                A = generate_pegasus(n)

        dir = DIR + "_matrix.txt"
        file = open(dir, 'a')
        i = 0
        for row in Q:
            i += 1
            print(f"--- Printing Q in file './{dir}' ... {int((i/n)*100)} %",
                  end='\r')
            file.write(str(row) + '\n')

        print(f"--- Printing Q in file './{dir}' END ---  ")
        file.close()
        d_min, eta, i_max, k, lambda_zero, n, N, N_max, p_delta, q, topology, Q, DIR, sim
        string = "\n --- DATA --- \ndmin = " + str(d_min) + " - eta = " + str(
            eta) + " - imax = " + str(i_max) + " - k = " + str(
                k) + " - lambda 0 = " + str(lambda_zero) + " - n = " + str(
                    n) + " - N = " + str(N) + " - Nmax = " + str(
                        N_max) + " - pdelta = " + str(p_delta) + "\n"
        print(string)
        write(DIR, string)

        I = np.identity(n)
        p = 1
        Theta_one, m_one = g(Q, A, np.arange(n), p, sim)
        Theta_two, m_two = g(Q, A, np.arange(n), p, sim)

        string = "Working on z1..."
        print(string, end=' ')
        write(DIR, string)
        start = time.time()
        z_one = map_back(annealer(Theta_one, sampler, k), m_one)
        convert_1 = datetime.timedelta(seconds=(time.time() - start))
        string = "Ended in " + str(convert_1) + " .\nWorking on z2..."
        print(string, end=' ')
        write(DIR, string)
        start = time.time()
        z_two = map_back(annealer(Theta_two, sampler, k), m_two)
        convert_2 = datetime.timedelta(seconds=(time.time() - start))
        string = "Ended in " + str(convert_2) + " ."
        print(string)
        write(DIR, string)

        f_one = function_f(Q, z_one).item()
        f_two = function_f(Q, z_two).item()

        if (f_one < f_two):
            z_star = z_one
            f_star = f_one
            m_star = m_one
            z_prime = z_two
        else:
            z_star = z_two
            f_star = f_two
            m_star = m_two
            z_prime = z_one
        if (f_one == f_two) == False:
            S = (np.outer(z_prime, z_prime) - I) + np.diagflat(z_prime)
        else:
            S = [[0 for col in range(n)] for row in range(n)]

    except KeyboardInterrupt:
        string = "KeyboardInterrupt occurred before cycle, closing program..."
        print(string)
        write(DIR, string)
        exit()

    e = 0
    d = 0
    i = 1
    lam = lambda_zero

    sum_time = 0

    while True:
        start_time = time.time()
        try:
            string = str(round(((i / i_max) * 100), 2)) + "% -- ETA: " + str(
                datetime.timedelta(seconds=((sum_time / (i - 1)) *
                                            (i_max - i - 1)))) + "\n"
        except:
            string = str(round(
                ((i / i_max) * 100), 2)) + "% -- ETA: not yet available\n"
        print(string)

        try:
            Q_prime = np.add(Q, (np.multiply(lam, S)))
            if (i % N == 0):
                p = p - ((p - p_delta) * eta)

            Theta_prime, m = g(Q_prime, A, m_star, p, sim)

            #for kindex in range(1, k+1):
            string = "Working on z'..."
            print(string, end=' ')
            write(DIR, string)
            start = time.time()
            z_prime = map_back(annealer(Theta_prime, sampler, k), m)
            convert_z = datetime.timedelta(seconds=(time.time() - start))
            string = "Ended in " + str(convert_z) + " ."
            print(string)
            write(DIR, string)
            #z_prime = run_annealer(Theta_prime, sampler)

            if make_decision(q):
                z_prime = h(z_prime, q)

            if (z_prime == z_star) == False:
                f_prime = function_f(Q, z_prime).item()
                if (f_prime < f_star):
                    tmp = z_prime.copy()
                    z_prime = z_star.copy()
                    z_star = tmp.copy()
                    f_star = f_prime
                    m_star = m
                    e = 0
                    d = 0
                    S = S + ((np.outer(z_prime, z_prime) - I) +
                             np.diagflat(z_prime))

                else:
                    d = d + 1
                    #if make_decision(sim_ann((p - p_delta), f_prime, f_star)): #
                    if make_decision((p - p_delta)**(f_prime - f_star)):
                        tmp = z_prime.copy()
                        z_prime = z_star.copy()
                        z_star = tmp.copy()
                        f_star = f_prime
                        m_star = m
                        e = 0
                lam = min(lambda_zero, (lambda_zero / (2 + (i - 1) - e)))
            else:
                e = e + 1

            # debug print
            converted = datetime.timedelta(seconds=(time.time() - start_time))

            try:
                if (n > 16):
                    string = "-- -- Valori ciclo " + str(i) + "/" + str(
                        i_max
                    ) + " -- --\np = " + str(p) + ", f_prime = " + str(
                        f_prime) + ", f_star = " + str(
                            f_star) + ", e = " + str(e) + ", d = " + str(
                                d) + ", Nmax = " + str(
                                    N_max) + ", dmin = " + str(
                                        d_min) + " e lambda = " + str(
                                            lam) + "\nCi ho messo " + str(
                                                converted) + " in totale\n"
                else:
                    string = "-- -- Valori ciclo " + str(i) + "/" + str(
                        i_max
                    ) + " -- --\np = " + str(p) + ", f_prime = " + str(
                        f_prime
                    ) + ", f_star = " + str(f_star) + ", e = " + str(
                        e) + ", d = " + str(d) + ", Nmax = " + str(
                            N_max
                        ) + ", dmin = " + str(d_min) + " e lambda = " + str(
                            lam) + "\nz* = " + str(z_star) + "\nz' = " + str(
                                z_prime) + "\nCi ho messo " + str(
                                    converted) + " in totale\n"
                print(string)
                write(DIR, string)
            except:
                if (n > 16):
                    string = "-- -- Valori ciclo " + str(i) + "/" + str(
                        i_max
                    ) + " -- --\nNon ci sono variazioni di f, z\ne = " + str(
                        e) + ", d = " + str(d) + ", Nmax = " + str(
                            N_max) + ", dmin = " + str(
                                d_min) + " e lambda = " + str(
                                    lam) + "\nCi ho messo " + str(
                                        converted) + " in totale\n"
                else:
                    string = "-- -- Valori ciclo " + str(i) + "/" + str(
                        i_max
                    ) + " -- --\nNon ci sono variazioni di f, z\ne = " + str(
                        e) + ", d = " + str(d) + ", Nmax = " + str(
                            N_max) + ", dmin = " + str(
                                d_min) + " e lambda = " + str(
                                    lam) + "\nz* = " + str(
                                        z_star) + "\nCi ho messo " + str(
                                            converted) + " in totale\n"
                print(string)
                write(DIR, string)

            dir = DIR + "_vector.txt"
            file = open(dir, 'a')
            file.write("Ciclo " + str(i) + "-esimo - z* --> " + str(z_star) +
                       "\n")
            file.close()
            sum_time = sum_time + (time.time() - start_time)

            if ((i == i_max) or ((e + d >= N_max) and (d < d_min))):
                if (i != i_max):
                    string = "Uscito al ciclo " + str(i) + "/" + str(
                        i_max) + " ed è stata raggiunta la convergenza."
                    print(string)
                    write(DIR, string)
                else:
                    string = "Uscito al ciclo " + str(i) + "/" + str(
                        i_max) + "\n"
                    print(string)
                    write(DIR, string)
                break

            i = i + 1
        except KeyboardInterrupt:
            #sum_time = sum_time + (time.time() - start_time)
            break

    converted = datetime.timedelta(seconds=sum_time)
    if i != 1:
        conv = datetime.timedelta(seconds=(sum_time / (i - 1)))
    else:
        conv = datetime.timedelta(seconds=(sum_time))
    string = "Tempo medio per iterazione: " + str(
        conv) + "\nTempo totale: " + str(converted) + "\n"
    print(string)
    write(DIR, string)

    return np.atleast_2d(z_star).T
Ejemplo n.º 13
0
#Minimum Vertex Cover
#Step one: Draw a single graph
#Imports include numpy, matplotlib, and networkx
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
a5 = nx.star_graph(4)
plt.subplot(121)
nx.draw(a5, with_labels=True, front_weight=’bold’)
#Step two: Solve the graphs minimum vertex cover
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
#Define sampler
sampler = EmbeddingComposite(DWaveSampler())
print(dnx.min_vertex_cover(a5, sampler))

#Factor
#Set an integer to factor
P = 21
#Binary representation of P 
bP = "{:06b}".format(P)
print(bP)
#Convert the CSP into BQM
csp = dbc.factories.multiplication_circuit(3)
bqm = dbc.stitch(csp, min_classical_gap=.1)
from helpers import draw
draw.circuit_from(bqm)
#Create variables
p_vars = ['p0', 'p1', 'p2', 'p3', 'p4', 'p5']
Ejemplo n.º 14
0
from minorminer import find_embedding
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import FixedEmbeddingComposite

# Set up the QUBO. Start with the equations from the slides:
# x + y - 2xy -1
# 2yz - y - z
# -2zx + z + x - 1
# QUBO: 2x - 2xy + 2yz - 2zx - 2
Q = {(0, 0): 2, (0, 1): -2, (0, 2): -2, (1, 2): 2}

chainstrength = 5
numruns = 1000

dwave_sampler = DWaveSampler()
A = dwave_sampler.edgelist
embedding = find_embedding(Q, A)
print(embedding)

response = FixedEmbeddingComposite(DWaveSampler(), embedding).sample_qubo(
    Q, chain_strength=chainstrength, num_reads=numruns)

for sample, energy, num, cbf in response.data(
    ['sample', 'energy', 'num_occurrences', 'chain_break_fraction']):
    print(sample, energy, num, cbf)
Ejemplo n.º 15
0
                same_bis = grid[:, x, y].flatten()
                if (x, y) in origin_list:
                    scale = w_sameori
                else:
                    scale = w_same
                sumLessOne(same_bis, J, scale=scale)

    # convert all 3 degree term to qubo form
    reduceBySubstitution(J, J_3D, 2)
    # show QUBO embedding
    print(J)

    if use_qpu:
        solver_limit = 205
        G = nx.complete_graph(solver_limit)
        system = DWaveSampler()
        embedding = minorminer.find_embedding(J.keys(), system.edgelist)
        print(embedding)
        res = QBSolv().sample_qubo(J,
                                   solver=FixedEmbeddingComposite(
                                       system, embedding),
                                   solver_limit=solver_limit,
                                   num_reads=5000)
        #res = EmbeddingComposite(DWaveSampler()).sample_qubo(J, num_reads=20)
    else:
        res = QBSolv().sample_qubo(J, num_repeats=2000)
    samples = list(res.samples())
    energy = list(res.data_vectors['energy'])
    print(samples[i])
    print(energy)
    energy, samples = zip(*sorted(zip(energy, samples), key=lambda k: k[0]))
Ejemplo n.º 16
0
    def __init__(self,
                 objective_function=None,
                 dwave_sampler=None,
                 dwave_sampler_kwargs=None,
                 num_activation_vectors=None,
                 activation_vec_hamming_dist=1,
                 max_hd=None,
                 parse_samples=True,
                 experiment_type=None,
                 num_reads=None,
                 num_iters=None,
                 network_type='minimum'):
        super().__init__(objective_function=objective_function)

        # Initialize switch network:
        # The default behavior here is to choose the smaller of either permutation or
        # sorting networks for the given input size.
        self.n_obj = self.objective_function.n
        if network_type == 'sorting':
            self.network = SortingNetwork(self.n_obj)
        elif network_type == 'permutation':
            self.network = PermutationNetwork(self.n_obj)
        elif network_type == 'minimum':
            s = SortingNetwork(self.n_obj)
            p = PermutationNetwork(self.n_obj)
            if s.depth <= p.depth:
                self.network = s
            else:
                self.network = p
        else:
            raise TypeError('Network type {} not recognized'.format(str(network_type)))
        self.n_qubo = self.network.depth
        self.dwave_solver = None
        self.sampler_kwargs = None
        self.qpu = False

        # Initialize dwave sampler:
        if dwave_sampler == 'QPU':
            self.dwave_solver = EmbeddingComposite(DWaveSampler())
            self.qpu = True
            if dwave_sampler_kwargs:
                self.sampler_kwargs = dwave_sampler_kwargs
            else:
                self.sampler_kwargs = dict()
        elif dwave_sampler == 'SA':
            self.dwave_solver = SimulatedAnnealingSampler()
            if num_reads:
                self.sampler_kwargs = {
                    'num_reads': num_reads
                }
            else:
                self.sampler_kwargs = {
                    'num_reads': 25
                }
        elif dwave_sampler == 'Tabu':
            self.dwave_solver = TabuSampler()
            if num_reads:
                self.sampler_kwargs = {
                    'num_reads': num_reads
                }
            else:
                self.sampler_kwargs = {
                    'num_reads': 250
                }

        self.stopwatch = 0

        # Initialize type of experiment
        # When running a timed experiment there is a high number of iterations and a 30 sec wall clock
        # When running a iteration experiment there is a iteration limit of 30 and no wall clock
        if experiment_type == 'time_lim':
            self.n_iters = 1000
            self.time_limit = 30

        if experiment_type == 'iter_lim' and num_iters:
            self.n_iters = num_iters
            self.time_limit = False
        else:
            self.n_iters = 50
            self.time_limit = False

        if max_hd:
            self.max_hd = max_hd
        else:
            self.max_hd = 0

        if num_activation_vectors:
            self.num_activation_vec = num_activation_vectors
        else:
            self.num_activation_vec = self.n_qubo

        self.form_qubo = LQUBO(objective_function=self.objective_function,
                               switch_network=self.network,
                               max_hamming_dist=self.max_hd,
                               num_activation_vectors=self.num_activation_vec,
                               activation_vec_hamming_dist=activation_vec_hamming_dist)

        self.solution = self.objective_function.min_v

        if parse_samples:
            self.selection = CheckAndSelect
        else:
            self.selection = Select
Ejemplo n.º 17
0
from minorminer import find_embedding
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import FixedEmbeddingComposite

# Graph partitioning as full mesh
gamma = 3
N = 8
linear = N - 1 - (7 * gamma)
quad = (2 * gamma) - 2

Q = {}
for i in range(N):
    Q[i, i] = linear
    for j in range(i + 1, N):
        Q[i, j] = quad

chainstrength = 5
numruns = 100

dwave_sampler = DWaveSampler()
A = dwave_sampler.edgelist
embedding = find_embedding(Q, A)
print(embedding)
Ejemplo n.º 18
0
# Uncomment if you need to paste in a solver and/or token
# my_solver = 'paste your solver in here'
# my_token = 'paste your token in here'

# Your default or manually set solver and token are used in the next cell. The cell sets a *sampler*, the component used to find variable values that minimize the Ising model representing our problem. Here we use a D-Wave system but Ocean tools are designed to swap in and out samplers with ease. For example you might first run a classical sampler on your computer's CPU during testing, and only once your code is ready, submit the problem for solution on the quantum computer.
#
# *DWaveSampler()* from Ocean software's [dwave-system](https://docs.ocean.dwavesys.com/projects/system/en/latest/) tool handles the connection to a D-Wave system. This tool also handles mapping between the graph of our problem, NetworkX's *complete_graph(4)* graph with nodes labeled Alice, Bob etc, to the D-Wave QPU's numerically indexed qubits. This mapping, known as *minor-embedding*, is done by the *EmbeddingComposite()* composite.

# In[ ]:

# Select a D-Wave system and handle mapping from problem graph to sampler graph
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite

sampler = EmbeddingComposite(DWaveSampler(solver=my_solver, token=my_token))

# ### Solving the Problem
# Next, the *structural_imbalance()* algorithm, from Ocean's [dwave_networkx](https://docs.ocean.dwavesys.com/projects/dwave-networkx/en/latest/) extension of the NetworkX graphic package, submits the Ising model we formulated in the previous section to a D-Wave system. It returns a partition of our social network into two colored sets and the frustrated edges.

# In[ ]:

# Return a good partition (minimal structural imbalance) and its frustrated edges
import dwave_networkx as dnx
imbalance, bicoloring = dnx.structural_imbalance(G, sampler)

# Mark the returned frustrated edges and node set (color) on the graph
for edge in G.edges:
    G.edges[edge]['frustrated'] = edge in imbalance
for node in G.nodes:
    G.nodes[node]['color'] = bicoloring[node]
Ejemplo n.º 19
0
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite

# Set up the QUBO. Start with the equations from the slides:
# x + y - 2xy -1
# 2yz - y - z
# -2zx + z + x - 1
# QUBO: 2x - 2xy + 2yz - 2zx - 2

chainstrength = 5
numruns = 100
Q = {(0, 0): 2, (0, 1): -2, (0, 2): -2, (1, 2): 2}

response = EmbeddingComposite(DWaveSampler()).sample_qubo(
    Q, chain_strength=chainstrength, num_reads=numruns)

for smpl, energy in response.data(['sample', 'energy']):
    print(smpl, energy)
        (20.0, 1.0)  # After 20us, set the anneal setting to 100% (max)
    )


# A custom anneal schedule can have up to four points.
def anneal_sched_custom_3():
    return (
        (0.0, 0.0),  # Start everything at 0
        (1.0, 0.80),  # Quickly ramp up to 80% anneal at 1µs
        (19.0, 0.81),  # From 1µs to 19µs, slowly go from 80% to 81%.
        (20.0, 1.0)  # End the full anneal at 20µs
    )


print('Boolean NOT Gate with Default Annealing Schedule')
sampler = DWaveSampler()
# We put a small bias for qubit 0 to see if the annealing schedule
# makes a difference in the distribution of solutions.
Q = {(0, 0): -1.1, (0, 4): 0, (4, 0): 2, (4, 4): -1}

response_1 = sampler.sample_qubo(Q,
                                 anneal_schedule=anneal_sched_custom_1(),
                                 num_reads=1000)
response_2 = sampler.sample_qubo(Q,
                                 anneal_schedule=anneal_sched_custom_2(),
                                 num_reads=1000)
response_3 = sampler.sample_qubo(Q,
                                 anneal_schedule=anneal_sched_custom_3(),
                                 num_reads=1000)

print('Anneal schedule 1:')
Ejemplo n.º 21
0
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
from itertools import combinations
Sampler = EmbeddingComposite(DWaveSampler())
#Eri Montano
#traveling sales man problem
#this is a 4 city problem and should work with more cities


#order of initial upper triangle for the city/weight order
distance = [4,6,5,1,4,7] 

E = len(distance) 

N = int((1+(1+E*8)**0.5)/2) #calcualte based on edges

cities = list(range(N))
 
gamma = 15.0 
chainstrength = 10
numruns = 100

edges = list(combinations(cities,2))

print (edges)


Q = {(a,b): 0 for a in range(E) for b in range(E)} 

for i in range(E): #form the diagonal
	Q[(i,i)] = distance[i]-(6*gamma)
Ejemplo n.º 22
0
N = int(sys.argv[1])
G = nx.complete_graph(N)

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 6))

# Draw the QUBO as a networkx graph
pos = nx.spring_layout(G)
nx.draw_networkx(G,
                 pos=pos,
                 font_size=10,
                 node_size=100,
                 node_color='cyan',
                 ax=axes[0])

# Embed the graph on Chimera
dwave_sampler_chimera = DWaveSampler(solver={'topology__type': 'chimera'})
chimera_edges = dwave_sampler_chimera.edgelist
chimera_graph = dnx.chimera_graph(16, edge_list=chimera_edges)
clique_embedding_chimera = find_clique_embedding(N, chimera_graph)

# Draw the graph embedded on Chimera
dnx.draw_chimera_embedding(chimera_graph,
                           clique_embedding_chimera,
                           embedded_graph=G,
                           unused_color=None,
                           ax=axes[1])

# Embed the graph on Pegasus
dwave_sampler_pegasus = DWaveSampler(solver={'topology__type': 'pegasus'})
pegasus_edges = dwave_sampler_pegasus.edgelist
pegasus_graph = dnx.pegasus_graph(16, edge_list=pegasus_edges)
Ejemplo n.º 23
0
 def setUpClass(cls):
     try:
         cls.qpu = DWaveSampler(solver=dict(flux_biases=True))
     except (ValueError, ConfigFileError):
         raise unittest.SkipTest("no qpu available")
Ejemplo n.º 24
0
def solve(Q, problem, is_simulated):
    print('IS_SIMULATED', is_simulated)
    sampler = neal.SimulatedAnnealingSampler() if  is_simulated else EmbeddingComposite(DWaveSampler(token=SAPI_TOKEN, endpoint=ENDPOINT, solver='DW_2000Q_2_1'))
    response = sampler.sample_qubo(Q, chain_strength=CHAIN_STRENGTH, num_reads=NUM_READS)
    return decode_solution(response, problem)
Ejemplo n.º 25
0
def execute(circuit,
            backend=None,
            config=None,
            basis_gates=None,
            coupling_map=None,
            initial_layout=None,
            shots=1024,
            max_credits=10,
            seed=None,
            qobj_id=None,
            hpc=None,
            skip_transpiler=False,
            seed_mapper=None):

    outputs = list()
    inputs = list()

    for qubit in circuit.annealergraph.qubits.keys():
        if isinstance(circuit.annealergraph.qubits[qubit], dict):
            if circuit.annealergraph.qubits[qubit]['measured'] == True:
                outputs.append(
                    circuit.annealergraph.qubits[qubit]['components'][-1])
                # can't omit output bit from being included as input, but is its put
                # first in the list, it will be zero the top portion of the readout
                inputs.append(
                    circuit.annealergraph.qubits[qubit]['components'][0])

    for qubit in circuit.annealergraph.qubits.keys():
        if isinstance(circuit.annealergraph.qubits[qubit], dict):
            if circuit.annealergraph.qubits[qubit]['measured'] == False:
                inputs.append(
                    circuit.annealergraph.qubits[qubit]['components'][0])

    sampler = DWaveSampler(
        endpoint='https://cloud.dwavesys.com/sapi',
        token='DEV-beb5d0babc40334f66b655704f1b5315917b4c41',
        solver='DW_2000Q_2_1')
    '''
    qubit_weights, coupler_weights, dwavemap = circuit.annealergraph.map_to_Dwave_graph(list(sampler._nodelist), list(sampler.edgelist))
    
    ins = list()
    outs = list()
    for name in inputs:
        ins.append(dwavemap[name][0])
    for name in outputs:
        outs.append(dwavemap[name][0])

    inputs = ins
    outputs = outs
    '''

    qubit_weights = circuit.annealergraph.qubitweights
    coupler_weights = circuit.annealergraph.couplerweights

    bqm = dimod.BinaryQuadraticModel(qubit_weights, coupler_weights, 0,
                                     dimod.BINARY)

    kwargs = {}
    if 'num_reads' in sampler.parameters:
        kwargs['num_reads'] = 100
    if 'answer_mode' in sampler.parameters:
        kwargs['answer_mode'] = 'histogram'
    print("Running...")

    response = EmbeddingComposite(sampler).sample(bqm, **kwargs)

    sampler.client.close()
    print("Done.")
    print(response.data)

    groundstate = 1000000
    for sample, energy in response.data(['sample', 'energy']):
        if energy < groundstate:
            groundstate = round(energy, 1)

    function = list()
    for sample, energy in response.data(['sample', 'energy']):
        if round(energy, 1) == groundstate:
            print(sample, round(energy, 1))
            row = []
            for inp in inputs:
                row.append(sample[inp])
            for outp in outputs:
                row.append(sample[outp])
            function.append(row)
    print('\n')

    function.sort()
    for i in range(len(function)):
        print(function[i])

    print(embedding)

    if len(circuit.annealergraph.qubitweights) < 18:
        # ExactSolver simulation
        print("\nExactSolver Check:")
        print("Simulating problem with {} qubits".format(
            len(circuit.annealergraph.qubitweights)))
        qubit_weights = circuit.annealergraph.qubitweights
        coupler_weights = circuit.annealergraph.couplerweights

        bqm = dimod.BinaryQuadraticModel(qubit_weights, coupler_weights, 0,
                                         dimod.BINARY)
        sampler = dimod.ExactSolver()

        response = sampler.sample(bqm)

        groundstate = 1000000
        for sample, energy in response.data(['sample', 'energy']):
            if energy < groundstate:
                groundstate = round(energy, 1)

        function = list()
        for sample, energy in response.data(['sample', 'energy']):
            if round(energy, 1) == groundstate:
                print(sample, round(energy, 1))
                row = []
                for inp in inputs:
                    row.append(sample[inp])
                for outp in outputs:
                    row.append(sample[outp])
                function.append(row)
        print('\n')

        function.sort()
        for i in range(len(function)):
            print(function[i])
    else:
        print("Problem to large to simulate. Used {} qubits".format(
            len(circuit.annealergraph.qubitweights)))
Ejemplo n.º 26
0
# Be sure to count them once for each segment
# s0 and s3
H += 2 * ((q[0, 0] + q[0, 1] + q[1, 0] + q[1, 1]) ** 2)
# s2 and s7 and s10
H += 3 * ((q[0, 2] + q[1, 2]) ** 2)
# s6 and s9
H += 2 * ((q[0, 0] + q[1, 0]) ** 2)
# s8
H += (q[0, 1] + q[1, 1]) ** 2
# s11
H += (q[0, 1] + q[0, 2] + q[1, 1] + q[1, 2]) ** 2

# Compile the model, and turn it into a QUBO object
model = H.compile()
Q = model.to_qubo(feed_dict={'gamma': 100})

# Turn the QUBO object into a BinaryQuadraticModel, using the computed
# offset
bqm = BinaryQuadraticModel.from_qubo(Q[0], offset=Q[1])

# Run the QUBO on the solver from your config file
response = EmbeddingComposite(DWaveSampler()).sample(bqm, chain_strength=chainstrength, num_reads=numruns)

# Write complete results to file
output = open('Traffic1_results.txt', 'w')
for smpl, energy in response.data(['sample', 'energy']):
    sol, broken, eny = model.decode_solution(smpl, feed_dict={'gamma': 100}, vartype='BINARY')
    if not broken:
        output.write(str(energy) + ' ' + str([node for node in smpl if smpl[node] > 0]) + '\n')
output.close()
Ejemplo n.º 27
0
# Import networkx for graph tools
import networkx as nx

# Import dwave_networkx for d-wave graph tools/functions
import dwave_networkx as dnx

# Import matplotlib.pyplot to draw graphs on screen
import matplotlib.pyplot as plt

# Set the solver we're going to use
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite

# it stops in this line below
sampler = EmbeddingComposite(DWaveSampler())

# Create empty graph
G = nx.Graph()

# Add edges to graph - this also adds the nodes
G.add_edges_from([(1, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 5), (4, 6),
                  (5, 6), (6, 7)])

# Find the maximum independent set, S
S = dnx.maximum_independent_set(G, sampler=sampler, num_reads=10)

# Print the solution for the user
print('Maximum independent set size found is', len(S))
print(S)

# Visualize the results
Ejemplo n.º 28
0
# Create a binary constraint satisfaction problem
csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

# Add constraint that each node (province) select a single color
for province in provinces:
    variables = [province+str(i) for i in range(colors)]
    csp.add_constraint(one_color_configurations, variables)

# Add constraint that each pair of nodes with a shared edge not both select one color
for neighbor in neighbors:
    v, u = neighbor
    for i in range(colors):
        variables = [v+str(i), u+str(i)]
        csp.add_constraint(not_both_1, variables)

# Convert the binary constraint satisfaction problem to a binary quadratic model
bqm = dwavebinarycsp.stitch(csp)

# Set up a solver using the local system’s default D-Wave Cloud Client configuration file
# and sample 50 times
sampler = EmbeddingComposite(DWaveSampler())         # doctest: +SKIP
response = sampler.sample(bqm, num_reads=50)         # doctest: +SKIP

# Plot the lowest-energy sample if it meets the constraints
sample = next(response.samples())      # doctest: +SKIP
if not csp.check(sample):              # doctest: +SKIP
    print("Failed to color map")
else:
    plot_map(sample)
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:
        #Calling dwave machines
        cant_connect = True
        while cant_connect:
            try:
                print('about to call remote')
                client = Client.from_config(token='secrettoken')
                solver = client.get_solvers()
                dwave_sampler = DWaveSampler(solver={'qpu': True})      # define sampler
                print('called remote {}'.format(dwave_sampler))
                print('solver', solver)
                cant_connect = False
            except IOError:
                print('Network error, trying again', datetime.datetime.now())
                time.sleep(10)
                cant_connect = True

        #Tuning annealing parameters
        dwave_sampler.parameters["annealing_time"] = a_time
        dwave_sampler.parameters["num_reads"] = nreads
        dwave_sampler.parameters["answer_mode"] = 'raw'

        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 = np.zeros((ngauges*nreads, len(h)))
        print("Number of variables to anneal :"+str(len(h)))
        for g in range(ngauges):
            #Finding embedding
            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(dwave_sampler)
                    embedded = True
                    break
                except ValueError:      # no embedding found
                    print('no embedding found')
                    embedded = False
                    continue

            if not embedded:
                continue

            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)
                    print(sampleset.info)
                    qaresults.append(sampleset.record[0][0].tolist())
                    energy.append(sampleset.record[0][1])
                    try_again = False
                except:
                    print('runtime or ioerror, trying again')
                    time.sleep(10)
                    try_again = True
            print("Quantum done")

            qaresults = qaresults * a
            qaresults[g*nreads:(g+1)*nreads] = qaresult

        full_strings= np.zeros((len(qaresults),len(C_i)))
        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 = 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]
        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])
Ejemplo n.º 30
0
print('Logic gate: 2 by 2 multiplier')
print('=============================')
print('Given virtual qubits a0, a1, b0, b1, c0, c1, c2, c3, c4;')
print('list possible solutions where:')
print('  C = A * B, and C = 9 (c3=1, c2=0, c1=0, c0=1)')
print('')

# At the top of this file, set useQpu to True to use a live QPU.
#
# For this tutorial we need a triangular configution, but the physical
# topology of the QPU does not have triangles. There is a technique
# called "embedding" that allows us to map our virtual problem onto a
# physical platform. The concept of embedding is described more
# thoroughly in the embedding tutorials.
if (useQpu):
    sampler = DWaveSampler()  # live QPU
    sampler_embedded = EmbeddingComposite(sampler)  # we will need to embed
    # See these pages for information on embedding:
    # https://docs.dwavesys.com/docs/latest/c_gs_4.html
    # https://docs.dwavesys.com/docs/latest/c_handbook_5.html
else:
    sampler = SimulatedAnnealingSampler()  # simulated quantum annealer
    sampler_embedded = sampler  # we do not need to embed for a simulation

csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

"""
Now we tie together logic gates and operators in the form of
constraints. Listing constraints is an easy way to get a problem onto
the D-Wave, but it is not necessarily an optimal way to do it.