-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsing_class.py
More file actions
73 lines (58 loc) · 2.45 KB
/
Ising_class.py
File metadata and controls
73 lines (58 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import numpy as np
from copy import deepcopy
from matplotlib import pyplot as plt
class Ising:
def __init__(self, N, seed = None):
self.N = N
## Optionally set up the random number generator state
if seed is not None:
np.random.seed(seed)
# s is the initial configuration vector
# The spins are arranged over a NxN lattice
s = np.ones((N,N), dtype=int)
self.s = s
self.init_config()
pass
## Initialize (or reset) the current configuration
def init_config(self):
N = self.N
self.s = np.random.choice([-1,1], size=(N,N))
## Definition of the cost function
# Here you need to complete the function computing the cost as described in the pdf file
# The cost function depends on the value of the spins and the values of their nearest neighbors
def cost(self):
N = self.N
s = self.s
energy = 0
for i in range(N):
for c in range(N):
energy += s[i,c] * s[(i-1)%N,c] + s[i,c] * s[(i+1)%N,c] + s[i,c] * s[i, (c-1)%N] + s[i,c] * s[i, (c+1)%N]
# cost = (s * (np.roll(s, 1, 0) + np.roll(s, -1, 0) +
# np.roll(s, 1, 1) + np.roll(s, -1, 1))).sum()
return -0.5*energy
## Propose a valid random move.
def propose_move(self):
N = self.N
move = (np.random.choice(N), np.random.choice(N))
return move
## Modify the current configuration, accepting the proposed move
def accept_move(self, move):
self.s[move] *= -1
## Compute the extra cost of the move (new-old, negative means convenient)
# Here you need complete the compute_delta_cost function as explained in the pdf file
# Check the constant in front of the delta cost
def compute_delta_cost(self, move):
s = self.s
N = self.N
i, c = move
alg_sum = s[(i-1)%N,c] + s[(i+1)%N,c] + s[i, (c-1)%N] + s[i, (c+1)%N]
delta_e = 2 * s[i,c] * (alg_sum)
return delta_e
## Make an entirely independent duplicate of the current object.
def copy(self):
return deepcopy(self)
## The display function is used for having a graphical representation of the configurations in white and black
def display(self):
plt.clf()
plt.imshow(self.s, cmap='gray', vmin=-1, vmax=1)
plt.show()