Rep:Mod:DMS3053-1
Appearance
CMP Programming Experiment - Daniel Spencer, 00736964
Python IsingLattice.py script - Calculating the energy and magnetisation
import numpy as np class IsingLattice:
E = 0.0
E2 = 0.0
M = 0.0
M2 = 0.0
n_cycles = 0
def __init__(self, n_rows, n_cols):
self.n_rows = n_rows
self.n_cols = n_cols
self.lattice = np.random.choice([-1,1], size=(n_rows, n_cols))
def energy(self): # Returns the total energy of the current lattice configuration.
J = 1.0 # Including this factor allows for potential modifications
summed_spins = 0
for i in range(len(self.lattice)): # Cycles through the rows of the spin array
for j in range(len(self.lattice[i])): # Cycles through the elements in the
#ith row of the spin array
if i + 1 < self.n_rows and j + 1 < self.n_cols: # Multiplies i,jth element
#with i+1,j and i,j+1 and adds to sum (applies to elements with two
#neighbours in the array)
summed_spins += self.lattice[i,j] * self.lattice[i+1,j]
summed_spins += self.lattice[i,j] * self.lattice[i,j+1]
elif i + 1 == self.n_rows and j + 1 < self.n_cols: # Multiplies i,jth
#element with 0,j (due to periodic nature of the lattice) and i,j+1
#(applies to elements in final row)
summed_spins += self.lattice[i,j] * self.lattice[0,j]
summed_spins += self.lattice[i,j] * self.lattice[i,j+1]
elif i + 1 < self.n_rows and j + 1 == self.n_cols: # Multiplies i,jth
#element with i+1,j and i,0 (applies elements in final column)
summed_spins += self.lattice[i,j] * self.lattice[i+1,j]
summed_spins += self.lattice[i,j] * self.lattice[i,0]
else: # Multiplied i,jth element with 0,j and i,0 (final array element -
#bottom right corner)
summed_spins += self.lattice[i,j] * self.lattice[0,j]
summed_spins += self.lattice[i,j] * self.lattice[i,0]
energy = - J * summed_spins
return energy
def magnetisation(self):
# Returns the total magnetisation of the current lattice configuration.
magnetisation = 0
for i in range(len(self.lattice)): # Cycles through the rows of the spin array
for j in range(len(self.lattice[i])): # Cycles through the elements in the
#ith row of the spin array
magnetisation += self.lattice[i,j] # Updates the running total of the
#magnetisation by adding i,jth value
return magnetisation
def montecarlostep(self, T):
# complete this function so that it performs a single Monte Carlo step
energy = self.energy()
#the following two lines will select the coordinates of the random spin for you
random_i = np.random.choice(range(0, self.n_rows))
random_j = np.random.choice(range(0, self.n_cols))
#the following line will choose a random number in the range [0,1) for you
random_number = np.random.random()
def statistics(self):
# complete this function so that it calculates the correct values for the averages of E, E*E (E2), M, M*M (M2), and returns them
return