main.py 2.1 KB
Newer Older
Q
Quleaf 已提交
1 2
# !/usr/bin/env python3
# Copyright (c) 2020 Institute for Quantum Computing, Baidu Inc. All Rights Reserved.
Q
Quleaf 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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.

Q
Quleaf 已提交
16
r"""
Q
Quleaf 已提交
17 18
main
"""
Q
Quleaf 已提交
19

Q
Quleaf 已提交
20 21
import numpy as np
import networkx as nx
Q
Quleaf 已提交
22
import matplotlib.pyplot as plt
Q
Quleaf 已提交
23
import paddle
Q
Quleaf 已提交
24
from paddle_quantum.QAOA.maxcut import maxcut_hamiltonian, find_cut
Q
Quleaf 已提交
25
from paddle_quantum.qinfo import pauli_str_to_matrix
Q
Quleaf 已提交
26

Q
Quleaf 已提交
27
SEED = 1024
Q
Quleaf 已提交
28 29 30 31 32 33 34 35
options = {
    "with_labels": True,
    "font_size": 20,
    "font_weight": "bold",
    "font_color": "white",
    "node_size": 2000,
    "width": 2
}
Q
Quleaf 已提交
36

Q
Quleaf 已提交
37 38

def main(n=4):
Q
Quleaf 已提交
39 40
    paddle.seed(SEED)
    
Q
Quleaf 已提交
41 42 43
    p = 4  # number of layers in the circuit
    ITR = 120  # number of iterations
    LR = 0.1    # learning rate
Q
Quleaf 已提交
44

Q
Quleaf 已提交
45 46 47 48 49 50 51 52 53 54
    G = nx.cycle_graph(4)
    V = list(G.nodes())
    E = list(G.edges())
    # Draw the original graph
    pos = nx.circular_layout(G)
    nx.draw_networkx(G, pos, **options)
    ax = plt.gca()
    ax.margins(0.20)
    plt.axis("off")
    plt.show()
Q
Quleaf 已提交
55

Q
Quleaf 已提交
56 57 58
    # construct the Hamiltonian
    H_D_list = maxcut_hamiltonian(E)
    H_D_matrix = pauli_str_to_matrix(H_D_list, n)
Q
Quleaf 已提交
59 60 61 62 63 64
    H_D_diag = np.diag(H_D_matrix).real
    H_max = np.max(H_D_diag)

    print(H_D_diag)
    print('H_max:', H_max)   

Q
Quleaf 已提交
65 66 67 68 69
    cut_bitstring, _ = find_cut(G, p, ITR, LR, print_loss=True, plot=True)
    print("The bit string form of the cut found:", cut_bitstring)

    node_cut = ["blue" if cut_bitstring[v] == "1" else "red" for v in V]
    edge_cut = ["solid" if cut_bitstring[u] == cut_bitstring[v] else "dashed" for (u, v) in G.edges()]
Q
Quleaf 已提交
70

Q
Quleaf 已提交
71
    nx.draw(G, pos, node_color=node_cut, style=edge_cut, **options)
Q
Quleaf 已提交
72 73 74 75
    ax = plt.gca()
    ax.margins(0.20)
    plt.axis("off")
    plt.show()
Q
Quleaf 已提交
76 77


Q
Quleaf 已提交
78
if __name__ == "__main__":
Q
Quleaf 已提交
79
    main()