1+ """
2+ This example demonstrates how to use the VQE algorithm to find the ground state
3+ of a 2D Heisenberg model on a square lattice. It showcases the setup of the lattice,
4+ the Heisenberg Hamiltonian, a suitable ansatz, and the optimization process.
5+ """
6+
17import time
28import optax
39import tensorcircuit as tc
713# Use JAX for high-performance, especially on GPU.
814K = tc .set_backend ("jax" )
915tc .set_dtype ("complex64" )
10- # On Windows, cotengra's multiprocessing can cause issues.
11- tc .set_contractor ("cotengra-8192-8192" , parallel = False )
16+ # On Windows, cotengra's multiprocessing can cause issues, use threads instead .
17+ tc .set_contractor ("cotengra-8192-8192" , parallel = "threads" )
1218
1319
1420def run_vqe ():
15- n , m , nlayers = 4 , 4 , 6
21+ """Set up and run the VQE optimization for a 2D Heisenberg model."""
22+ n , m , nlayers = 4 , 4 , 2
1623 lattice = SquareLattice (size = (n , m ), pbc = True , precompute_neighbors = 1 )
1724 h = heisenberg_hamiltonian (lattice , j_coupling = [1.0 , 1.0 , 0.8 ]) # Jx, Jy, Jz
1825 nn_bonds = lattice .get_neighbor_pairs (k = 1 , unique = True )
1926 gate_layers = get_compatible_layers (nn_bonds )
27+ n_params = nlayers * len (nn_bonds ) * 3
2028
2129 def singlet_init (circuit ):
2230 # A good initial state for Heisenberg ground state search
@@ -36,22 +44,26 @@ def vqe_forward(param):
3644 """
3745 c = tc .Circuit (n * m )
3846 c = singlet_init (c )
47+ param_idx = 0
3948
40- for i in range (nlayers ):
49+ for _ in range (nlayers ):
4150 for layer in gate_layers :
4251 for j , k in layer :
43- c .rzz (int (j ), int (k ), theta = param [i , 0 ])
52+ c .rzz (int (j ), int (k ), theta = param [param_idx ])
53+ param_idx += 1
4454 for layer in gate_layers :
4555 for j , k in layer :
46- c .rxx (int (j ), int (k ), theta = param [i , 1 ])
56+ c .rxx (int (j ), int (k ), theta = param [param_idx ])
57+ param_idx += 1
4758 for layer in gate_layers :
4859 for j , k in layer :
49- c .ryy (int (j ), int (k ), theta = param [i , 2 ])
60+ c .ryy (int (j ), int (k ), theta = param [param_idx ])
61+ param_idx += 1
5062
5163 return tc .templates .measurements .operator_expectation (c , h )
5264
5365 vgf = K .jit (K .value_and_grad (vqe_forward ))
54- param = tc .backend .implicit_randn (stddev = 0.02 , shape = [nlayers , 3 ])
66+ param = tc .backend .implicit_randn (stddev = 0.02 , shape = [n_params ])
5567 optimizer = optax .adam (learning_rate = 3e-3 )
5668 opt_state = optimizer .init (param )
5769
0 commit comments