Skip to content

Commit 343fdcc

Browse files
authored
imag time qaoa and fix H2 training. (#13)
1 parent a237c95 commit 343fdcc

File tree

3 files changed

+55
-4
lines changed

3 files changed

+55
-4
lines changed

examples/QAOA/QAOA.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
# required packages: NLopt, SCS and Convex
12
using Yao, BitBasis
23
using NLopt
34

examples/QAOA/imag_time_evolve.jl

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""imaginary time evolution solution to maximum cut problem."""
2+
using Yao
3+
4+
@const_gate ZZ = mat(kron(Z,Z))
5+
6+
function maxcut_circuit(W::AbstractMatrix, τ)
7+
nbit = size(W, 1)
8+
ab = chain(nbit)
9+
for i=1:nbit,j=i+1:nbit
10+
if W[i,j] != 0
11+
#push!(ab, put(nbit, (i,j)=>0.5*W[i,j]*ZZ))
12+
push!(ab, put(nbit, (i,j)=>rot(ZZ, -im*W[i,j]*τ)))
13+
end
14+
end
15+
return ab
16+
end
17+
18+
function maxcut_h(W::AbstractMatrix)
19+
nbit = size(W, 1)
20+
ab = Add{nbit}()
21+
for i=1:nbit,j=i+1:nbit
22+
if W[i,j] != 0
23+
#push!(ab, put(nbit, (i,j)=>0.5*W[i,j]*ZZ))
24+
push!(ab, put(nbit, (i,j)=>0.5*W[i,j]*ZZ))
25+
end
26+
end
27+
return ab
28+
end
29+
30+
using Random, Test
31+
@testset "iqaoa circuit" begin
32+
Random.seed!(2)
33+
nbit = 5
34+
# exact solution is [(1,3,4), (2,5)]
35+
W = [0 5 2 1 0;
36+
5 0 3 2 0;
37+
2 3 0 0 0;
38+
1 2 0 0 4;
39+
0 0 0 4 0]
40+
41+
c = maxcut_circuit(W, 10)
42+
h = maxcut_h(W)
43+
reg = uniform_state(nbit) |> c
44+
45+
# check the correctness of result
46+
opt_pl = reg |> probs
47+
config = argmax(opt_pl)-1
48+
@show BitStr64{nbit}(config), opt_pl[config+1]
49+
@test config == bit"01101" || config == bit"10010"
50+
@test isapprox(expect(h, reg |> normalize!), -5.5)
51+
end

examples/VQE/H2.jl

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
using Yao
2-
32
using YaoExtensions
43

54
# arXiv: 1704.05018, table S2
@@ -20,13 +19,13 @@ end
2019

2120
using Flux: Optimise
2221
function train!(circ, hamiltonian; optimizer, niter::Int=100)
23-
circ = circ |> autodiff(:BP)
2422
params = parameters(circ)
2523
dispatch!(circ, :random)
2624
for i=1:niter
27-
Optimise.update!(optimizer, params, get_gradient(circ, hamiltonian))
25+
_, grad = expect'(hamiltonian, zero_state(nqubits(circ)) => circ)
26+
Optimise.update!(optimizer, params, grad)
2827
dispatch!(circ, params)
29-
println("Energy = $(expect(hamiltonian, zero_state(nqubits(h)) |> circ))")
28+
println("Energy = $(expect(hamiltonian, zero_state(nqubits(h)) |> circ) |> real)")
3029
end
3130
return expect(hamiltonian, zero_state(nqubits(h)) |> circ)
3231
end

0 commit comments

Comments
 (0)