コード例 #1
0
    def solve(self):

        if (self.useQPU):
            sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
            sampleset = sampler.sample_qubo(self.Q,
                                            num_reads=self.n_reads,
                                            chain_strength=self.chain)
        elif (self.useNeal):
            bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset)
            sampler = neal.SimulatedAnnealingSampler()
            sampleset = sampler.sample(bqm,
                                       num_reads=self.n_reads,
                                       chain_strength=self.chain)
        elif (self.useHyb):
            bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset)
            sampler = LeapHybridSampler()
            sampleset = sampler.sample(bqm, num_reads=self.n_reads)
        else:
            bqm = BinaryQuadraticModel.from_qubo(self.Q, offset=self.offset)
            sampler = TabuSampler()
            sampleset = sampler.sample(bqm,
                                       num_reads=self.n_reads,
                                       chain_strength=self.chain)

        self.sampleset = sampleset
コード例 #2
0
    def test_initial_state(self):
        sampler = EmbeddingComposite(self.qpu)

        bqm = dimod.BinaryQuadraticModel.from_ising({'a': 2.0, 'b': -2.0},
                                                    {('a', 'b'): -1})

        kwargs = {'initial_state': {'a': 1, 'b': 1},
                  'anneal_schedule': [(0, 1), (55.0, 0.45),
                                      (155.0, 0.45), (210.0, 1)]}

        sampler.sample(bqm, **kwargs).resolve()
コード例 #3
0
    def test_many_bqm_async(self):
        sampler = EmbeddingComposite(self.qpu)

        # in the future it would be good to test a wide variety of BQMs,
        # see https://github.com/dwavesystems/dimod/issues/671
        # but for now let's just test a few
        bqm0 = dimod.BinaryQuadraticModel.from_ising({
            'a': 2.0,
            'b': -2.0
        }, {('a', 'b'): -1})
        bqm1 = dimod.BinaryQuadraticModel.from_ising({2: 4}, {
            (0, 1): 1.5,
            (1, 2): 5
        })

        samplesets0 = []
        samplesets1 = []
        for _ in range(10):
            # this should be async
            samplesets0.append(sampler.sample(bqm0))
            samplesets1.append(sampler.sample(bqm1))

        if all(ss.done() for ss in samplesets0):
            warnings.warn("Sampler calls appear to be synchronous")

        for ss0, ss1 in zip(samplesets0, samplesets1):
            dimod.testing.assert_sampleset_energies(ss0, bqm0)
            dimod.testing.assert_sampleset_energies(ss1, bqm1)

        self.assertTrue(all(ss.done() for ss in samplesets0))
        self.assertTrue(all(ss.done() for ss in samplesets1))
コード例 #4
0
def objective(trial):
    b1 = trial.suggest_uniform('b1', 0.0, 20)
    b2 = trial.suggest_uniform('b2', 0.0, 20)
    b3 = trial.suggest_uniform('b3', 0.0, 20)

    def_dict = {
        "balancer1": b1,
        "balancer2": b2,
        "balancer3": b3,
        "IntChain": 1.0
    }
    bqm = model.to_dimod_bqm(feed_dict=def_dict)

    sampler = EmbeddingComposite(DWaveSampler(sampler="DW_2000Q_6"))
    responses = sampler.sample(bqm, num_reads=5000)

    solutions = model.decode_dimod_response(responses, feed_dict=def_dict)

    cnt = 0

    for idx, sol in enumerate(solutions):
        if len(sol[1]) < 10:
            cnt += responses.record[idx][2]

    return cnt
コード例 #5
0
def test_quantum2():
    ''' Example using D-Wave's quantum annealing
    
    Note: Embedding is done with the use of D-Wave composite
    '''
    X = np.array([[1, 2], [1, 3], [9, 5], [9, 6]])  # input data
    k = 2
    model = genModel(X, k)  # generate BQM model (not yet embedded)
    sampler = EmbeddingComposite(DWaveSampler(
        solver={'qpu': True
                }))  # sets D-Wave's sampler, embedding is done automatically
    solution_set = sampler.sample(
        model, num_reads=100,
        return_embedding=True)  # run on the D-wave hardware
    print("Embedding: ", solution_set.info["embedding_context"]["embedding"])
    # Count the number of qubits used
    num_qubits = 0
    for entry in solution_set.info["embedding_context"]["embedding"].values():
        num_qubits += len(entry)
    print("Number of qubits: ", num_qubits)
    M, assignments = postprocess2(
        X, solution_set.first.sample)  # postprocess the solution
    print("Centroids: ")
    print(M)
    print("Assignments: " + str(assignments))
コード例 #6
0
def cluster_points(scattered_points, filename):
    # Set up problem
    # Note: max_distance gets used in division later on. Hence, the max(.., 1)
    #   is used to prevent a division by zero
    coordinates = [Coordinate(x, y) for x, y in scattered_points]
    max_distance = max(get_max_distance(coordinates), 1)

    # Build constraints
    csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

    # Apply constraint: coordinate can only be in one colour group
    choose_one_group = {(0, 0, 1), (0, 1, 0), (1, 0, 0)}
    for coord in coordinates:
        csp.add_constraint(choose_one_group, (coord.r, coord.g, coord.b))

    # Build initial BQM
    bqm = dwavebinarycsp.stitch(csp)

    # Edit BQM to bias for close together points to share the same color
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            d = get_distance(coord0, coord1) / max_distance  # rescale distance
            weight = -math.cos(d * math.pi)

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.b, weight)

    # Edit BQM to bias for far away points to have different colors
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            # Note: rescaled and applied square root so that far off distances
            #   are all weighted approximately the same
            d = math.sqrt(get_distance(coord0, coord1) / max_distance)
            weight = -math.tanh(d) * 0.1

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.b, weight)
            bqm.add_interaction(coord0.r, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.r, weight)
            bqm.add_interaction(coord0.b, coord1.g, weight)
            bqm.add_interaction(coord0.g, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.b, weight)

# Submit problem to D-Wave sampler
    sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
    #sampler = neal.SimulatedAnnealingSampler()
    sampleset = sampler.sample(bqm, chain_strength=4, num_reads=1000)
    best_sample = sampleset.first.sample

    # Visualize graph problem
    dwave.inspector.show(bqm, sampleset)

    # Visualize solution
    groupings = get_groupings(best_sample)
    visualize_groupings(groupings, filename)
    return groupings
コード例 #7
0
ファイル: flightHelper.py プロジェクト: jmalliaros/Enigma
    def solve(self, 
              useQPU=False, 
              useNeal=False, 
              useHyb=True,
              time_limit = 10,
              num_reads = 100,
              chain_strength = 10000):
        
        Q = self.Q
        BQM_offset = 0 # TODO: Use the accumulated quadratic constants from the constraints

        bqm = BinaryQuadraticModel.from_qubo(Q, offset=BQM_offset)

        self.sampleset = None
        
        # Call the requested solver
        
        if ( useQPU ):
            print("Solving using the DWaveSampler on the QPU...")
            sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
            sampleset = sampler.sample_qubo(Q, num_reads=num_reads,chain_strength = chain_strength)
        elif ( useHyb ): 
            print("Solving using the LeapHybridSolver...")
            sampler = LeapHybridSampler()
            sampleset = sampler.sample(bqm, time_limit = time_limit)
        elif ( useNeal ): 
            print("Solving using the SimulatedAnnealing...")
            sampler = neal.SimulatedAnnealingSampler()
            sampleset = sampler.sample(bqm, num_reads = num_reads)
        else:
            print("Solving using the TabuSampler...")
            sampler = TabuSampler()
            sampleset = sampler.sample(bqm, num_reads = num_reads)

        self.sampleset = sampleset
        
        count = 0
        for res in self.sampleset.data(): count += 1
        
        return (count)
コード例 #8
0
def factor(P):
    bP = "{:06b}".format(P)
    csp = dbc.factories.multiplication_circuit(3)
    bqm = dbc.stitch(csp, min_classical_gap=.1)
    p_vars = ['p0', 'p1', 'p2', 'p3', 'p4', 'p5']
    fixed_variables = dict(zip(reversed(p_vars), bP))
    fixed_variables = {var: int(x) for (var, x) in fixed_variables.items()}
    for var, value in fixed_variables.items():
        bqm.fix_variable(var, value)

    sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
    sampleset = sampler.sample(bqm, num_reads=1000)
    a, b = to_base_ten(sampleset.first.sample)
    print("Given integer P={0}, found factors a={1} and b={2}".format(P, a, b))
    return a, b
コード例 #9
0
ファイル: KnapsackProblemPulp.py プロジェクト: 84monta/OR
    def optimize_advantage(self,count=False,Best=0,balancer=1.0):
        from pyqubo import Array,Constraint,Placeholder,UnaryEncInteger,Sum #LogEncInteger
        from dwave.system import EmbeddingComposite,DWaveSampler

        x = Array.create("x",shape=(self.num),vartype="BINARY")
        #y = LogEncInteger("y",lower=0,upper=5)
        y = UnaryEncInteger("y",lower=0,upper=5)

        #価値が最大になるように(符号を反転させる)
        #H1 = -sum([x[i]*self.p[i].get_value() for i in range(self.num)])
        H1 = -Sum(0,self.num,lambda i :x[i]*self.p[i].get_value() )

        #重さが目的の重量になるように
        #H2 = Constraint((self.limit_weight -sum([x[i]*p_i.get_weight() for i,p_i in enumerate(self.p)]) - y*10)**2,"Const Weight")
        H2 = Constraint((self.limit_weight -Sum(0,self.num,lambda i: x[i]*self.p[i].get_weight()) - y*10)**2,"Const Weight")
        #H2 = Constraint((self.limit_weight -Sum(0,self.num,lambda i: x[i]*self.p[i].get_weight()))**2,"Const Weight")

        H = H1 + H2*Placeholder("balancer")
        model = H.compile()
        balance_dict = {"balancer":balancer}
        bqm = model.to_dimod_bqm(feed_dict=balance_dict)
        sampler = EmbeddingComposite(DWaveSampler(solver="Advantage_system1.1"))
        #sampler = EmbeddingComposite(DWaveSampler(solver="DW_2000Q_6"))
        responses = sampler.sample(bqm,num_reads=1000)

        solutions = model.decode_dimod_response(responses,feed_dict=balance_dict)
        #Optuna用 バランス調査
        if count == True:
            counter = 0
            for idx,sol in enumerate(solutions):
                const_str = sol[1]
                val = sum(int(sol[0]['x'][i])*self.p[i].get_value()  for i in range(self.num))
                weight = sum(int(sol[0]['x'][i])*self.p[i].get_weight()  for i in range(self.num))
                #重量が制限以下、かつ価値が最適解の9割以上をカウント
                if len(const_str) == 0 and val > Best*0.9 and weight <= self.limit_weight:
                    counter += responses.record[idx][2]

            del H1,H2,H,model,bqm,responses,solutions
            gc.collect()

            return counter

        if len(solutions[0][1]) == 0:
            print(f" y= { sum(2**i*y_i for i,y_i in enumerate(solutions[0][0]['y']))}")
            print("## Advantage Solver Optimized Result")
            self.print([int(solutions[0][0]['x'][i]) for i in range(self.num)])
        else:
            print("## Advantage Solver Optimizing Failed")
コード例 #10
0
# Creo la seconda parte dell'Hamiltoniana creando e unendo
# tutti i vincoli per le coppie di provincie vicine
H2 = colori_diversi(neighbours[len(neighbours) - 1][0],
                    neighbours[len(neighbours) - 1][1])
for i in range(len(neighbours) - 1):
    H2 = H2 + colori_diversi(neighbours[i][0], neighbours[i][1])

# Creo l'Hamiltoniana e la faccio diventare una BQM
model = H1 + H2
bqm = model.compile().to_bqm()

# Creo il set dei risultati utilizzando il sampler definito prima
chainstrenght = None
sampleset = sampler.sample(bqm,
                           num_reads=20,
                           chain_strength=chainstrenght,
                           label="Problema della mappa")

#risultati
#print(sampleset)

# Uso l'inspector
dwave.inspector.show(sampleset)

# Seleziono il risultato migliore, ossia quello a energia minore
risultato = sampleset.first.sample

#print(risultato)
#print(risultato[0])

# Creo un grafo vuoto
コード例 #11
0
# --------------------------------------------------------------------------#

# This program demonstrates a basic Ocean program that runs a QUBO problem on
# the D-Wave QPU as a binary quadratic model (BQM).

# --------------------------------------------------------------------------#

# Import the functions and packages that are used
from dwave.system import EmbeddingComposite, DWaveSampler
from dimod import BinaryQuadraticModel

# Define the problem as a Python dictionary and convert it to a BQM
Q = {('B','B'): 1,
    ('K','K'): 1,
    ('A','C'): 2,
    ('A','K'): -2,
    ('B','C'): -2}

# Convert the problem to a BQM
bqm = BinaryQuadraticModel.from_qubo(Q)

# Define the sampler that will be used to run the problem
sampler = EmbeddingComposite(DWaveSampler())

# Run the problem on the sampler and print the results
sampleset = sampler.sample(bqm,
                           num_reads = 10,
                           label='Example - Simple Ocean Programs: BQM')
print(sampleset)
コード例 #12
0
def backup(expName, topo, samples):

    with open("data/" + expName + topo + str(datetime.now()), "wb") as f:

        pickle.dump(samples, f)


arr = [4, 4, 8, 4, 4, 8]
#np.random.randint(1,high=100,size=20)
print(arr)
H = 0

for i in range(len(arr)):
    H += arr[i] * Spin(f'x_{i}')

H *= H
model = H.compile()
sampler = DWaveSampler()
embedded = EmbeddingComposite(sampler)
bqm = model.to_bqm()  # we need pyqubo>=1.0.0

print("embedding and sampling...")
sampleset = embedded.sample(bqm, num_reads=100)
backup("num partitioning arr", "Chimera", arr)
backup("num partitioning", "Chimera", sampleset)
decoded_samples = model.decode_sampleset(sampleset)
best = min(decoded_samples, key=lambda x: x.energy)
# decision version of the partitioning problemm: does there exist a partition?
print(best)
# how close are we?
print(best.energy)
コード例 #13
0
    nodes = list(i for i in range(24))
    edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8),
             (8, 9), (9, 10), (10, 11), (0, 11), (0, 12), (1, 13), (2, 14),
             (3, 15), (4, 16), (5, 17), (6, 18), (7, 19), (8, 20), (9, 21),
             (10, 22), (11, 23), (12, 16), (12, 20), (13, 17), (13, 21),
             (14, 18), (14, 22), (15, 19), (15, 23), (16, 20), (17, 21),
             (18, 22), (19, 23)]

    #####################

    G = create_graph(edges)
    bqm = get_bqm(nodes, edges)

    # Define the sampler and run the problem
    sampler = EmbeddingComposite(DWaveSampler())
    sample_set = sampler.sample(bqm)

    # Print the solution
    # print(sample_set)
    result = list(sample_set.first.sample[i] for i in nodes)
    vertices = []
    for i in range(len(result)):
        if result[i] == 1:
            vertices.append(i)
    print('Maximum independent set size found is', (len(vertices)))
    print(vertices)

    # Visualize the results
    subset_1 = G.subgraph(vertices)
    notVertices = list(set(G.nodes()) - set(vertices))
    subset_0 = G.subgraph(notVertices)
コード例 #14
0
def run(bqm, num_reads):
    sampler = EmbeddingComposite(DWaveSampler())
    response = sampler.sample(bqm, num_reads)
    return get_response(response)
コード例 #15
0
ファイル: clustering.py プロジェクト: palmcorp/clustering
def cluster_points(scattered_points, filename, problem_inspector):
    """Perform clustering analysis on given points

    Args:
        scattered_points (list of tuples):
            Points to be clustered
        filename (str):
            Output file for graphic
        problem_inspector (bool):
            Whether to show problem inspector
    """
    # Set up problem
    # Note: max_distance gets used in division later on. Hence, the max(.., 1)
    #   is used to prevent a division by zero
    coordinates = [Coordinate(x, y) for x, y in scattered_points]
    max_distance = max(get_max_distance(coordinates), 1)

    # Build constraints
    csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

    # Apply constraint: coordinate can only be in one colour group
    choose_one_group = {(0, 0, 1), (0, 1, 0), (1, 0, 0)}
    for coord in coordinates:
        csp.add_constraint(choose_one_group, (coord.r, coord.g, coord.b))

    # Build initial BQM
    bqm = dwavebinarycsp.stitch(csp)

    # Edit BQM to bias for close together points to share the same color
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            d = get_distance(coord0, coord1) / max_distance  # rescale distance
            weight = -math.cos(d * math.pi)

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.b, weight)

    # Edit BQM to bias for far away points to have different colors
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            # Note: rescaled and applied square root so that far off distances
            #   are all weighted approximately the same
            d = math.sqrt(get_distance(coord0, coord1) / max_distance)
            weight = -math.tanh(d) * 0.1

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.b, weight)
            bqm.add_interaction(coord0.r, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.r, weight)
            bqm.add_interaction(coord0.b, coord1.g, weight)
            bqm.add_interaction(coord0.g, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.b, weight)

    # Submit problem to D-Wave sampler
    sampler = EmbeddingComposite(DWaveSampler())
    sampleset = sampler.sample(bqm,
                               chain_strength=4,
                               num_reads=1000,
                               label='Example - Clustering')
    best_sample = sampleset.first.sample

    # Visualize graph problem
    if problem_inspector:
        dwave.inspector.show(bqm, sampleset)

    # Visualize solution
    groupings = get_groupings(best_sample)
    visualize_groupings(groupings, filename)

    # Print solution onto terminal
    # Note: This is simply a more compact version of 'best_sample'
    print(groupings)
コード例 #16
0
def run_qca_minimal(E_k=1,
                    qpu_arch='pegasus',
                    use_classical=False,
                    num_reads=10,
                    show_inspector=False,
                    plot_emb_path=None,
                    h_array=[-1, 0],
                    J_matrix=[[0, 1], [1, 0]]):
    '''
    Minimal 1 Driver 2 Cell QCA Problem (introduced in the Leap slide deck).

    Params:
        E_k : kink energy in eV.
        qpu_arch : QPU architecture to use. Either 'pegasus' (that is the newer
            architecture) or 'chimera' (the old one).
        use_classical : set to True to use D-Wave's classical Ising solver such 
            that you don't have to use up your D-Wave Leap minutes for testing.
        num_reads : count of samples to request from the D-Wave QPU or classical
            sampler. Don't use too high of a value on the QPU as that might 
            use up your Leap minutes very quickly.
        show_inspector : set to True to show problem inspector in the end.
        plot_emb_path : supply a string path to plot the embedding
    '''
    import matplotlib.pyplot as plt

    # general dwave dependencies
    import dwave
    import dwave.embedding
    import dwave.inspector
    from dwave.system import DWaveSampler, EmbeddingComposite
    from dwave.cloud import Client
    from dwave.cloud.exceptions import SolverNotFoundError
    import dimod
    from dimod.reference.samplers import ExactSolver
    from minorminer import find_embedding
    import neal

    # dependencies for plotting connectivity graph
    import networkx as nx
    import dwave_networkx as dnx

    # general math and Python dependencies
    import math
    import numpy as np
    import itertools

    # define self bias (h) and coupling strengths (J)
    h = -E_k * np.array(h_array)
    J = -E_k * np.array(J_matrix)
    N = len(h)

    # create edgelist (note that {} initializes Python dicts)
    linear = {}  # qubit self-bias
    quadratic = {}  # inter-qubit bias
    for i in range(N):
        linear[i] = h[i]
        for j in range(i + 1, N):
            if J[i][j] != 0:
                quadratic[(i, j)] = J[i][j]

    # construct a bqm containing the provided self-biases (linear) and couplings
    # (quadratic). Specify the problem as SPIN (Ising).
    print('Constructing BQM...')
    bqm = dimod.BinaryQuadraticModel(linear, quadratic, 0, dimod.SPIN)

    # get DWave sampler and target mapping edgelist
    print('Choosing solver...')
    client = Client.from_config()
    solver = None
    try:
        if qpu_arch == 'pegasus':
            solver = client.get_solver('Advantage_system1.1').id
        elif qpu_arch == 'chimera':
            solver = client.get_solver('DW_2000Q_6').id
        else:
            raise ValueError('Specified QPU architecture is not supported.')
    except SolverNotFoundError:
        print(f'The pre-programmed D-Wave solver name for architecture '
              '\'{qpu_arch}\' is not available. Find the latest available '
              'solvers by:\n'
              'from dwave.cloud import Client\nclient = Client.from_config()\n'
              'client.get_solvers()\nAnd update this script.')
        raise
    # get the specified QPU
    dwave_sampler = DWaveSampler(solver=solver)

    # run the problem
    sampler = None
    response = None
    if use_classical:
        print('Choosing classical sampler...')
        sampler = neal.SimulatedAnnealingSampler()
    else:
        print('Choosing D-Wave QPU as sampler...')
        sampler = EmbeddingComposite(dwave_sampler)
    response = sampler.sample(bqm, num_reads=num_reads)
    # print(response)
    print('Problem completed from selected sampler.')

    # plot the embedding if specified
    if not use_classical and plot_emb_path != None:
        print(f'Plotting embedding to {plot_emb_path}...')
        embedding = response.info['embedding_context']['embedding']
        plt.figure(figsize=(16, 16))
        T_nodelist, T_edgelist, T_adjacency = dwave_sampler.structure
        if qpu_arch == 'pegasus':
            G = dnx.pegasus_graph(16, node_list=T_nodelist)
            dnx.draw_pegasus_embedding(G,
                                       embedding,
                                       node_size=8,
                                       cmap='rainbow')
        elif qpu_arch == 'chimera':
            G = dnx.chimera_graph(16, node_list=T_nodelist)
            dnx.draw_chimera_embedding(G,
                                       embedding,
                                       node_size=8,
                                       cmap='rainbow')
        plt.savefig(plot_emb_path)

    # take first result from response
    use_result = [*response.first.sample.values()]
    # NOTE that response.record contains all returned results and some
    # statistics. You can inspect what's inside by using pdb or reading the
    # dimod.SampleSet documentation.

    # show dwave web inspector if specified
    if show_inspector and not use_classical:
        print('\nOpening problem inspector on your browser.')
        dwave.inspector.show(response)
    return response
コード例 #17
0
#%%
qubo_small

#%%
bqm_small = dimod.BQM.from_qubo(qubo_small)

#%%
bqm_small

#%%
from dwave.system import DWaveSampler, EmbeddingComposite

#%%
qpu = DWaveSampler()

#%%
sampler = EmbeddingComposite(qpu,
                             embedding_parameters={
                                 'timeout': 10,
                                 'tries': 1
                             })

#%%
result = sampler.sample(bqm_small)

#%%
result

#%%
コード例 #18
0
def factor(P):
    # Construct circuit
    # =================
    construction_start_time = time.time()

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

    # Constraint satisfaction problem
    # where the number of
    csp = dbc.factories.multiplication_circuit(4)

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

    # multiplication_circuit() creates these variables
    p_vars = ['p0', 'p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7']
    binary = "{:0" + str(8) + "b}"
    # Convert P from decimal to binary
    fixed_variables = dict(zip(reversed(p_vars), binary.format(P)))
    fixed_variables = {var: int(x) for (var, x) in fixed_variables.items()}
    print("fixed variables")
    print(fixed_variables)
    # Fix product qubits
    for var, value in fixed_variables.items():
        print(var, value)
        bqm.fix_variable(var, value)

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

    # Run problem
    # ===========

    sample_time = time.time()

    # Set a QPU sampler
    sampler = EmbeddingComposite(DWaveSampler())

    num_reads = 1000
    sampleset = sampler.sample(bqm, num_reads=num_reads)

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

    # Output results
    # ==============

    output = {
        "Results": [],
        #    {
        #        "a": Number,
        #        "b": Number,
        #        "Valid": Boolean,
        #        "Occurrences": Number,
        #        "Percentage of results": Number
        #    }
        "Timing": {
            "Actual": {
                "QPU processing time": None  # microseconds
            }
        },
        "Number of reads": None
    }

    # multiplication_circuit() creates these variables
    a_vars = ['a0', 'a1', 'a2', 'a3']
    b_vars = ['b0', 'b1', 'b2', 'b3']

    results_dict = OrderedDict()
    for sample, num_occurrences in sampleset.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]
        # Cast from numpy.int to int
        a, b = int(a), int(b)
        # Aggregate results by unique A and B values (ignoring internal circuit variables)
        if (a, b, P) in results_dict:
            results_dict[(a, b, P)]["Occurrences"] += num_occurrences
            results_dict[(a, b, P)]["Percentage of results"] = 100 * \
                                                               results_dict[(a, b, P)]["Occurrences"] / num_reads
        else:
            # if a * b == P:
            results_dict[(a, b, P)] = {
                "a": a,
                "b": b,
                "Valid": a * b == P,
                "Occurrences": num_occurrences,
                "Percentage of results": 100 * num_occurrences / num_reads
            }

    output['Results'] = list(results_dict.values())
    output['Number of reads'] = num_reads

    output['Timing']['Actual']['QPU processing time'] = sampleset.info[
        'timing']['qpu_access_time']

    return output
コード例 #19
0
ファイル: binlin.py プロジェクト: sctkjrc/quantum_unfolding
            for k in range(j):
                bqm.add_interaction(j, k, scaling * 2 * A[i, j] * A[i, k])

    return bqm


# setup
n = 11
A, b = setup_random(n)
# A, b = setup_easy()
scaling = 1.0 / n
chain_strength = 1.0
num_reads = 10000
# sampling
bqm = binlin(A, b, scaling=scaling)
samples = sampler.sample(bqm, num_reads=num_reads).aggregate()
# brute-force exact solution
bestx, minnorm = bruteforce(A, b)
# results
print("A =", A)
print("b =", b)
print("Brute-force solution:", bestx, "norm:", minnorm)
print()

idxbest = None
for idx, sample in enumerate(samples.record.sample):
    isvalid = np.linalg.norm(sample - bestx) == 0
    if isvalid:
        idxbest = idx
        print("Solution #{} (valid = {})".format(idx, isvalid))
        print("Sample:", sample)
コード例 #20
0
ファイル: willxujun.py プロジェクト: sploiber/inspector
import dimod
from dimod import BinaryQuadraticModel
from dwave.system import DWaveSampler, EmbeddingComposite
import dwave.inspector
import numpy as np

with open("willxujun.data", "r") as myfile:
    data = myfile.read()
z2 = [int(k) for k in data.split()]
arr = np.array(z2)
numpy_matrix = arr.reshape(64, 64)

bqm = dimod.BinaryQuadraticModel.from_numpy_matrix(numpy_matrix)
sampler = EmbeddingComposite(DWaveSampler())
sampleset = sampler.sample(bqm, chain_strength=10000, num_reads=1000)
dwave.inspector.show(bqm, sampleset, sampler)
コード例 #21
0
import dimod
import dwave.inspector
from dwave.system import DWaveSampler, EmbeddingComposite

# define problem
bqm = dimod.BQM.from_ising({}, {'ab': 1, 'bc': 1, 'ca': 1})

# get sampler
print("sampler init")
sampler = EmbeddingComposite(DWaveSampler())

# sample
print("sampling")
sampleset = sampler.sample(bqm,
                           num_reads=100,
                           chain_strength=1,
                           label='bqm/sampleset inspector example')

# inspect
print("inspecting")
dwave.inspector.show(bqm, sampleset)
コード例 #22
0
#https://docs.ocean.dwavesys.com/en/stable/examples/multi_gate.html
import dwavebinarycsp


def strange(a, b):
    return a or not b


csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

csp.add_constraint(strange, ['a', 'b'])
bqm = dwavebinarycsp.stitch(csp)

from dwave.system import DWaveSampler, EmbeddingComposite
sampler = EmbeddingComposite(DWaveSampler())

dataset = sampler.sample(bqm, num_reads=10)

print(dataset)
コード例 #23
0
def cluster_points(scattered_points, filename):
    # Set up problem
    coordinates = [Coordinate(x, y) for x, y in scattered_points]
    max_distance = get_max_distance(coordinates)

    # Build constraints
    csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

    # Apply constraint: coordinate can only be in one colour group
    choose_one_group = allowed_States(k)
    for coord in coordinates:
        mylist = list(vars(coord).values())
        mylist.remove(coord.x)
        mylist.remove(coord.y)

        csp.add_constraint(choose_one_group, mylist)

    # Build initial BQM
    bqm = dwavebinarycsp.stitch(csp)

    # Edit BQM to bias for close together points to share the same color
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            d = get_distance(coord0, coord1) / max_distance  # rescale distance
            weight = -math.cos(d * math.pi)

            # Apply weights to BQM

            for i in range(k):
                bqm.add_interaction(getattr(coord0, "x" + str(i)),
                                    getattr(coord1, "x" + str(i)), weight)

    # Edit BQM to bias for far away points to have different colors
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            # Note: rescaled and applied square root so that far off distances
            #   are all weighted approximately the same
            d = math.sqrt(get_distance(coord0, coord1) / max_distance)
            weight = -math.tanh(d) * 0.1

            # Apply weights to BQM
            for p in range(k):
                for m in range(k):
                    if p != m:
                        bqm.add_interaction(getattr(coord0, "x" + str(p)),
                                            getattr(coord1, "x" + str(m)),
                                            weight)

    # Submit problem to D-Wave sampler
    sampler = EmbeddingComposite(DWaveSampler(solver={'qpu': True}))
    sampleset = sampler.sample(bqm, chain_strength=4, num_reads=1000)
    best_sample = sampleset.first.sample

    # Visualize graph problem
    dwave.inspector.show(bqm, sampleset)

    # Visualize solution
    groupings = get_groupings(best_sample)
    visualize_groupings(groupings, filename)

    # Print solution onto terminal
    # Note: This is simply a more compact version of 'best_sample'
    print(groupings)
コード例 #24
0
def factor(P, gap_size, max_graph_size, size_of_circuit):
    # Construct circuit
    # =================
    construction_start_time = time.time()
    extra_number = 1

    # Constraint satisfaction problem

    """Normal Case CSP"""
    csp = dbc.factories.multiplication_circuit(size_of_circuit)

    # Binary quadratic model
    bqm = dbc.stitch(csp, max_graph_size=max_graph_size, min_classical_gap=gap_size)

    # multiplication_circuit() creates these variables
    p_vars = make_array(size_of_circuit * 2, 'p')
    a_vars = make_var_array(size_of_circuit, 'a')
    b_vars = make_var_array(size_of_circuit, 'b')
    binary = "{:0" + str(size_of_circuit * 2) + "b}"
    # Convert P from decimal to binary
    fixed_variables = dict(zip(reversed(p_vars), binary.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)
    bqm.fix_variable('a0', 1)
    bqm.fix_variable('b0', 1)

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

    # Run problem
    # ===========
    sample_time = time.time()

    # # Set a local sampler
    # sampler = neal.SimulatedAnnealingSampler()

    # Set a QPU sampler
    sampler = EmbeddingComposite(DWaveSampler())

    num_reads = 2000
    print("running localy")
    sampleset = sampler.sample(bqm, num_reads=num_reads)

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

    # Output results
    # ==============

    output = {
        "Results": [],
        #    {
        #        "a": Number,
        #        "b": Number,
        #        "Valid": Boolean,
        #        "Occurrences": Number,
        #        "Percentage of results": Number
        #    }
        "Timing": {
            "Actual": {
                "QPU processing time": None  # microseconds
            }
        },
        "Number of reads": None
    }

    # multiplication_circuit() creates these variables

    results_dict = OrderedDict()
    for sample, num_occurrences in sampleset.data(['sample', 'num_occurrences']):
        # Convert A and B from binary to decimal
        a = b = 0
        bitA = bitB = ""
        for lbl in reversed(a_vars):
            a = (a << 1) | sample[lbl]
            bitA += str(sample[lbl])
        for lbl in reversed(b_vars):
            b = (b << 1) | sample[lbl]
            bitB += str(sample[lbl])
        # Cast from numpy.int to int

        a, b = int((a << 1)), int((b << 1))
        a += extra_number
        b += extra_number
        bitA = bitA + "1"
        bitB = bitB + "1"
        # a, b = int(a + 2 ** (size_of_circuit-1) + 2 ** 0), int(a + 2 ** (size_of_circuit-1) + 2 ** 0)

        # Aggregate results by unique A and B values (ignoring internal circuit variables)
        if (a, b, P) in results_dict:
            results_dict[(a, b, P)]["Occurrences"] += num_occurrences
            results_dict[(a, b, P)]["Percentage of results"] = 100 * \
                                                               results_dict[(a, b, P)]["Occurrences"] / num_reads
        else:
            # if a * b == P:
            results_dict[(a, b, P)] = {
                "a": a,
                "b": b,
                "bitA": bitA,
                "bitB": bitB,
                "product": a * b,
                "Valid": a * b == P,
                "Occurrences": num_occurrences,
                "Percentage of results": 100 * num_occurrences / num_reads}
        # elif a == 659 or b == 659 or a == 571 or b == 571:
        #         results_dict[(a, b, P)] = {
        #             "a": a,
        #             "b": b,
        #             "bitA": bitA,
        #             "bitB": bitB,
        #             "product": a * b,
        #             "Valid": a * b == P,
        #             "Occurrences": num_occurrences,
        #             "Percentage of results": 100 * num_occurrences / num_reads}
        # else:
        #     wrong_A = wrong_A + 1
        # results_dict[(a, b, P)] = {"a": a,
        #                            "b": b,
        #                            "Valid": a * b == P,
        #                            "Occurrences": num_occurrences,
        #                            "Percentage of results": 100 * num_occurrences / num_reads}

    output['Results'] = list(results_dict.values())
    output['Number of reads'] = num_reads
    # pprint(output['Results'])
    # pprint(results_dict)
    # output['Timing']['Actual']['QPU processing time'] = sampleset.info['timing']['qpu_access_time']
    save_data(P, 'DW_2000Q+OneBit', size_of_circuit, gap_size, max_graph_size, output)

    return output, csp
コード例 #25
0
csp = full_adder(csp, "a1", "b1", "cin", "0")
csp = full_adder(csp, "a2", "b2", "0_cout", "1")
csp = full_adder(csp, "a3", "b3", "1_cout", "2")
csp = full_adder(csp, "a4", "b4", "2_cout", "3")
csp = full_adder(csp, "a5", "b5", "3_cout", "4")
csp = full_adder(csp, "a6", "b6", "4_cout", "5")
csp = full_adder(csp, "a7", "b7", "5_cout", "6")
csp = full_adder(csp, "a8", "b8", "6_cout", "7")
csp = full_adder(csp, "a9", "b9", "7_cout", "8")
csp = full_adder(csp, "a10", "b10", "8_cout", "9")

for i in range(0, 9):
    csp.fix_variable("sum" + str(i), 1)

csp.fix_variable("9_cout", 1)

bqm = dbc.stitch(csp)

sampler = EmbeddingComposite(DWaveSampler(solver={"qpu": True}))
sampleset = sampler.sample(bqm, num_reads=10000)
print(sampleset)

for sample, energy in sampleset.data(["sample", "energy"]):
    string = ""
    for i in range(1, 10):
        string += "a" + str(i) + ": " + str(sample["a" + str(i)]) + ", "
        string += "b" + str(i) + ": " + str(sample["b" + str(i)]) + ", "
    string += "cin: " + str(sample["cin"]) + " energy: " + str(energy)
    print(string)

dwave.inspector.show(sampleset)
コード例 #26
0
def factor(P, gap_size, max_graph_size, size_of_circuit):
    # Construct circuit
    # =================
    construction_start_time = time.time()

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

    # Constraint satisfaction problem
    # where the number of
    csp = dbc.factories.multiplication_circuit(size_of_circuit)

    # Binary quadratic model
    bqm = dbc.stitch(csp,
                     min_classical_gap=gap_size,
                     max_graph_size=max_graph_size)

    # multiplication_circuit() creates these variables
    p_vars = make_array(size_of_circuit * 2, 'p')
    binary = "{:0" + str(size_of_circuit * 2) + "b}"
    # Convert P from decimal to binary
    fixed_variables = dict(zip(reversed(p_vars), binary.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()
    # # Set a local sampler
    # sampler = neal.SimulatedAnnealingSampler()

    # Set a QPU sampler
    sampler = EmbeddingComposite(DWaveSampler())

    num_reads = 2000
    print("Sent to D-Wave")
    sampleset = sampler.sample(bqm, num_reads=num_reads)

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

    # Output results
    # ==============

    output = {
        "Results": [],
        #    {
        #        "a": Number,
        #        "b": Number,
        #        "Valid": Boolean,
        #        "Occurrences": Number,
        #        "Percentage of results": Number
        #    }
        "Timing": {
            "Actual": {
                "QPU processing time": None  # microseconds
            }
        },
        "Number of reads": None
    }

    # multiplication_circuit() creates these variables
    a_vars = make_array(size_of_circuit, 'a')
    b_vars = make_array(size_of_circuit, 'b')
    wrong_A = 0
    results_dict = OrderedDict()
    for sample, num_occurrences in sampleset.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]
        # Cast from numpy.int to int
        a, b = int(a), int(b)
        # Aggregate results by unique A and B values (ignoring internal circuit variables)
        if (a, b, P) in results_dict:
            results_dict[(a, b, P)]["Occurrences"] += num_occurrences
            results_dict[(a, b, P)]["Percentage of results"] = 100 * \
                                                               results_dict[(a, b, P)]["Occurrences"] / num_reads
        else:
            # if a * b == P:
            # results_dict[(a, b, P)] = {a, b, a * b == P, num_occurrences, 100 * num_occurrences / num_reads}
            results_dict[(a, b, P)] = {
                "a": a,
                "b": b,
                "Valid": a * b == P,
                "Occurrences": num_occurrences,
                "Percentage of results": 100 * num_occurrences / num_reads
            }
        # else:
        #     wrong_A = wrong_A + 1
        # results_dict[(a, b, P)] = {"a": a,
        #                            "b": b,
        #                            "Valid": a * b == P,
        #                            "Occurrences": num_occurrences,
        #                            "Percentage of results": 100 * num_occurrences / num_reads}

    output['Results'] = list(results_dict.values())
    output['Number of reads'] = num_reads

    # output['Timing']['Actual']['QPU processing time'] = sampleset.info['timing']['qpu_access_time']
    save_data(P, 'Advantage_system1.1', size_of_circuit, gap_size,
              max_graph_size, output)
    return output
コード例 #27
0
def cluster_points(scattered_points, filename, architecture):
    # Set up problem
    # Note: max_distance gets used in division later on. Hence, the max(.., 1)
    #   is used to prevent a division by zero
    coordinates = [Coordinate(x, y) for x, y in scattered_points]
    max_distance = max(get_max_distance(coordinates), 1)

    # Build constraints
    csp = dwavebinarycsp.ConstraintSatisfactionProblem(dwavebinarycsp.BINARY)

    # Apply constraint: coordinate can only be in one colour group
    choose_one_group = {(0, 0, 1), (0, 1, 0), (1, 0, 0)}
    for coord in coordinates:
        csp.add_constraint(choose_one_group, (coord.r, coord.g, coord.b))

    # Build initial BQM
    bqm = dwavebinarycsp.stitch(csp)

    # Edit BQM to bias for close together points to share the same color
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            d = get_distance(coord0, coord1) / max_distance  # rescale distance
            weight = -math.cos(d * math.pi)

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.b, weight)

    # Edit BQM to bias for far away points to have different colors
    for i, coord0 in enumerate(coordinates[:-1]):
        for coord1 in coordinates[i + 1:]:
            # Set up weight
            # Note: rescaled and applied square root so that far off distances
            #   are all weighted approximately the same
            d = math.sqrt(get_distance(coord0, coord1) / max_distance)
            weight = -math.tanh(d) * 0.1

            # Apply weights to BQM
            bqm.add_interaction(coord0.r, coord1.b, weight)
            bqm.add_interaction(coord0.r, coord1.g, weight)
            bqm.add_interaction(coord0.b, coord1.r, weight)
            bqm.add_interaction(coord0.b, coord1.g, weight)
            bqm.add_interaction(coord0.g, coord1.r, weight)
            bqm.add_interaction(coord0.g, coord1.b, weight)

    # Submit problem to D-Wave sampler
    if architecture == 'pegasus':
        solver = DWaveSampler(solver={
            'topology__type': 'pegasus',
            'qpu': True
        })
        print(solver.solver)

        sampler = EmbeddingComposite(solver)
    else:
        solver = DWaveSampler(solver={
            'topology__type': 'chimera',
            'qpu': True
        })
        print(solver.solver)

        sampler = EmbeddingComposite(solver)

    sampleset = sampler.sample(bqm,
                               chain_strength=4,
                               num_reads=1000,
                               return_embedding=True)
    best_sample = sampleset.first.sample

    # Inspect the embedding
    embedding = sampleset.info['embedding_context']['embedding']
    num_qubits = 0

    for k in embedding.values():
        num_qubits += len(k)
    print("Number of qubits used in embedding = " + str(num_qubits))

    # Visualize graph problem
    dwave.inspector.show(bqm, sampleset)

    # Visualize solution
    groupings = get_groupings(best_sample)
    visualize_groupings(groupings, filename)

    # Print solution onto terminal
    # Note: This is simply a more compact version of 'best_sample'
    print(groupings)
コード例 #28
0
study.optimize(objective, n_trials=200)

b1 = study.best_params["b1"]
b2 = study.best_params["b2"]
b3 = study.best_params["b3"]

def_dict = {
    "balancer1": b1,
    "balancer2": b2,
    "balancer3": b3,
    "IntChain": 10.0
}
bqm = model.to_dimod_bqm(feed_dict=def_dict)

sampler = EmbeddingComposite(DWaveSampler(sampler="DW_2000Q_6"))
responses = sampler.sample(bqm, num_reads=1000)

#sampler = LeapHybridSampler()
#responses = sampler.sample(bqm,time_limit=60)

solutions = model.decode_dimod_response(responses, feed_dict=def_dict)

cnt = 0

for sol in solutions:
    if len(sol[1]) < 10:
        weight_const_flag = False
        for i in range(n):
            if sum(sol[0]['x'][i][j] * a[i, j] for j in range(m)) > b[i]:
                weight_const_flag = True
コード例 #29
0
ファイル: sixx.py プロジェクト: sploiber/inspector
from dijkstra_solver import dijkstra_solver
import networkx as nx
from dimod import BinaryQuadraticModel
import dimod
import dwave.inspector
from dwave.system import DWaveSampler, EmbeddingComposite

G = nx.Graph()
G.add_weighted_edges_from([('S', 'a', 4.0), ('a', 'b', 7.0), ('b', 'G', 2.0),
                           ('G', 'd', 3.0), ('c', 'd', 8.0), ('c', 'S', 6.0),
                           ('c', 'b', 9.0)])
lagrange = 20
chainstrength = 20
numruns = 1000

model = dijkstra_solver(G, 'S', 'G', lagrange)
Q = model.to_qubo()
bqm = BinaryQuadraticModel.from_qubo(Q[0], offset=Q[1])
sampler = EmbeddingComposite(DWaveSampler())
sampleset = sampler.sample(bqm,
                           chain_strength=chainstrength,
                           num_reads=numruns)
dwave.inspector.show(bqm, sampleset, sampler)
コード例 #30
0
ファイル: bqm_optimizer.py プロジェクト: cslr/clustering
NVAR = 50

## hi = {0: 1, 1: -1, 2: .5}
## Jji = { (0,1): .5, (1,2): .5, (0,2): -0.5 }

hi = {}
Jji = {}

for i in range(NVAR):
    hi[i] = random.random()
    for j in range(i + 1, NVAR):
        Jji[(j, i)] = random.random()

print("{} parameters in Ising model.".format(str(len(Jji) + len(hi))))

# another parameter value is dimod.Vartype.BINARY for 0/1 valued variables
bqm = dimod.BinaryQuadraticModel(hi, Jji, 0.0, dimod.Vartype.SPIN)

print("Sampling model..")

sampler = EmbeddingComposite(DWaveSampler())
sampleset = sampler.sample(bqm,
                           chain_strength=4,
                           num_reads=1000,
                           label='BQM/Ising model test')

best_sample = sampleset.first.sample

print(best_sample)