I am attempting to apply my CasinoTime function to each position in my array per sweep. The function currently does this but chooses a position at random and can only do one position per sweep. The output looks something like this:
Starting Configuration: [[ 1 -1 1 1 -1 -1 1 1 1 -1]]
0: [[ 1 -1 1 1 -1 -1 1 1 1 -1]] Energy: [-2] Spin: 0.2
1: [[ 1 -1 1 1 1 -1 1 1 1 -1]] Energy: [[-10]] Spin: 0.4
2: [[ 1 -1 1 1 1 -1 1 1 1 -1]] Energy: [[-10]] Spin: 0.4
3: [[-1 -1 1 1 1 -1 1 1 1 -1]] Energy: [[-2]] Spin: 0.2
As you can see, it only alters one position at a time. Ideally my function will run through every position in my array (per sweep) and change the values which meet the criteria. This is a simulation of A Monte Carlo/Metropolis Algorithm. I have attempted to use a map function to apply my function to my array however this does not seem to work. Any help is greatly appreciated and I have attached my code below!
import numpy as np
N = 10
J = 1
H = 2
def calcEnergy(config, J, H):
energy = 0
for i in range(config.size):
spin = config[i]
neighbour = config[(i + 1) % N]
energy = energy - J * (spin * neighbour) - H * neighbour
return energy
def ChangeInEnergy(J, H, spin, spinleft, spinright):
dE = 2 * H * spin + 2 * J * spin * (spinleft + spinright)
return dE
def CasinoTime(sweeps, beta, J, H, debug=False):
config = np.random.choice([-1, 1], (N, 1))
averagespins = []
if debug is True:
print("Starting Configuration:", (np.transpose(config)))
runningenergy = calcEnergy(config, J, H)
for i in range(sweeps):
spinlocation = np.random.randint(N)
spin = config[spinlocation]
spinright = config[(spin + 1) % N]
spinleft = config[(spin - 1) % N]
dE = ChangeInEnergy(J, H, spin, spinleft, spinright)
r = np.random.random()
if r < min(1, np.exp(-beta * dE)):
config[spinlocation] *= -1
runningenergy = runningenergy + dE
else:
pass
averagespin = config.mean()
if debug and i % 1 == 0:
print("%i: " % i, np.transpose(config), "Energy:", runningenergy, "Spin:", averagespin)
return averagespins
averagespins = CasinoTime(sweeps=20, beta=0.1, J=1, H=2, debug=True)