コード例 #1
0
 def test_cplex_ising_direct(self):
     """ cplex ising direct test """
     try:
         algo = CPLEX_Ising(self.algo_input.qubit_op, display=0)
         result = algo.run()
         self.assertEqual(result['energy'], -20.5)
         x_dict = result['x_sol']
         x = np.array([x_dict[i] for i in sorted(x_dict.keys())])
         np.testing.assert_array_equal(max_cut.get_graph_solution(x),
                                       [1, 0, 1, 1])
         self.assertEqual(max_cut.max_cut_value(x, self.w), 24)
     except AquaError as ex:
         self.skipTest(str(ex))
コード例 #2
0
 def test_cplex_ising_via_run_algorithm(self):
     try:
         params = {
             'problem': {
                 'name': 'ising'
             },
             'algorithm': {
                 'name': 'CPLEX.Ising',
                 'display': 0
             }
         }
         result = run_algorithm(params, self.algo_input)
         self.assertEqual(result['energy'], -20.5)
         x_dict = result['x_sol']
         x = np.array([x_dict[i] for i in sorted(x_dict.keys())])
         np.testing.assert_array_equal(max_cut.get_graph_solution(x),
                                       [1, 0, 1, 1])
         self.assertEqual(max_cut.max_cut_value(x, self.w), 24)
     except AquaError as e:
         self.skipTest(str(e))
コード例 #3
0
def qiskit_maxcut():
    n = 4  # Number of nodes in graph
    G = nx.Graph()
    G.add_nodes_from(np.arange(0, n, 1))
    elist = [(0, 1, 1.0), (0, 2, 1.0), (0, 3, 1.0), (1, 2, 1.0), (2, 3, 1.0)]
    # tuple is (i,j,weight) where (i,j) is the edge
    G.add_weighted_edges_from(elist)

    colors = ['r' for node in G.nodes()]
    pos = nx.spring_layout(G)
    default_axes = plt.axes(frameon=True)
    nx.draw_networkx(G,
                     node_color=colors,
                     node_size=600,
                     alpha=.8,
                     ax=default_axes,
                     pos=pos)
    w = np.zeros([n, n])
    for i in range(n):
        for j in range(n):
            temp = G.get_edge_data(i, j, default=0)
            if temp != 0:
                w[i, j] = temp['weight']
    # print(w)  # weight matrix. i.e. distances. 0 indicates no path.

    #####
    # Brute force solution
    # best_cost_brute = 0
    # for b in range(2 ** n):
    #     x = [int(t) for t in reversed(list(bin(b)[2:].zfill(n)))]
    #     cost = 0
    #     for i in range(n):
    #         for j in range(n):
    #             cost = cost + w[i, j] * x[i] * (1 - x[j])
    #     if best_cost_brute < cost:
    #         best_cost_brute = cost
    #         xbest_brute = x
    #     print('case = ' + str(x) + ' cost = ' + str(cost))
    #
    # colors = ['r' if xbest_brute[i] == 0 else 'b' for i in range(n)]
    # nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)
    # print('\nBest solution = ' + str(xbest_brute) + ' cost = ' + str(best_cost_brute))
    # End brute force solution
    #####

    #####
    # Eigensolver solution
    # qubitOp, offset = max_cut.get_max_cut_qubitops(w)
    # algo_input = EnergyInput(qubitOp)
    #
    # # Making the Hamiltonian in its full form and getting the lowest eigenvalue and eigenvector
    # ee = ExactEigensolver(qubitOp, k=1)
    # result = ee.run()
    #
    # """
    # algorithm_cfg = {
    #     'name': 'ExactEigensolver',
    # }
    #
    # params = {
    #     'problem': {'name': 'ising'},
    #     'algorithm': algorithm_cfg
    # }
    # result = run_algorithm(params,algo_input)
    # """
    # x = max_cut.sample_most_likely(result['eigvecs'][0])
    # print('energy:', result['energy'])
    # print('maxcut objective:', result['energy'] + offset)
    # print('solution:', max_cut.get_graph_solution(x))
    # print('solution objective:', max_cut.max_cut_value(x, w))
    #
    # colors = ['r' if max_cut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)]
    # nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)
    # End eigensolver solution
    #####

    # run quantum algorithm with shots
    qubitOp, offset = max_cut.get_max_cut_qubitops(w)
    algo_input = EnergyInput(qubitOp)
    seed = 10598

    spsa = SPSA(max_trials=300)
    ry = RY(qubitOp.num_qubits, depth=5, entanglement='linear')
    vqe = VQE(qubitOp, ry, spsa, 'grouped_paulis')

    backend = Aer.get_backend('qasm_simulator')
    quantum_instance = QuantumInstance(backend=backend, shots=1024, seed=seed)

    result = vqe.run(quantum_instance)
    """declarative approach, update the param from the previous cell.
    params['algorithm']['operator_mode'] = 'grouped_paulis'
    params['backend']['name'] = 'qasm_simulator'
    params['backend']['shots'] = 1024
    result = run_algorithm(params, algo_input)
    """

    x = max_cut.sample_most_likely(result['eigvecs'][0])
    print('energy:', result['energy'])
    print('time:', result['eval_time'])
    print('maxcut objective:', result['energy'] + offset)
    print('solution:', max_cut.get_graph_solution(x))
    print('solution objective:', max_cut.max_cut_value(x, w))
    plot_histogram(result['eigvecs'][0])

    colors = [
        'r' if max_cut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)
    ]
    nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, pos=pos)
コード例 #4
0
                                   seed_transpiler=seed)

result = vqe.run(quantum_instance)
"""declarative approach, update the param from the previous cell.
params['backend']['provider'] = 'qiskit.BasicAer'
params['backend']['name'] = 'qasm_simulator'
params['backend']['shots'] = 1024
result = run_algorithm(params, algo_input)
"""

x = max_cut.sample_most_likely(result['eigvecs'][0])
print('energy:', result['energy'])
print('time:', result['eval_time'])
print('max-cut objective:', result['energy'] + offset)
print('solution:', max_cut.get_graph_solution(x))
print('solution objective:', max_cut.max_cut_value(x, w))
plot_histogram(result['eigvecs'][0])

colors = [
    'r' if max_cut.get_graph_solution(x)[i] == 0 else 'b' for i in range(n)
]
pos = nx.spring_layout(G)
nx.draw(G,
        pos,
        with_labels=True,
        node_color=colors,
        edge_color='gray',
        width=7,
        node_size=500,
        font_size=8,
        font_color='black')