├── IsingGrid.py ├── LICENSE ├── README.md └── main.py /IsingGrid.py: -------------------------------------------------------------------------------- 1 | """ 2 | This file defines Ising Grid class 3 | Created: Mar. 30, 2019 4 | Last Edited: Apr. 3, 2019 5 | By Bill 6 | """ 7 | 8 | import numpy as np 9 | 10 | 11 | class Grid(object): 12 | """Grid is a 2-D, periodic-boundaried and square canvas consisting of spins""" 13 | """Initial Grid only consists of positive spins""" 14 | 15 | def __init__(self, size, Jfactor): 16 | self.size = size 17 | self.Jfactor = Jfactor 18 | self.canvas = np.ones([size, size], int) 19 | 20 | def randomize(self): 21 | self.canvas = np.random.randint(0, 2, [self.size, self.size]) * 2 - 1 22 | 23 | def set_positive(self): 24 | self.canvas = np.ones([self.size, self.size], int) 25 | 26 | def set_negative(self): 27 | self.canvas = -np.ones([self.size, self.size], int) 28 | 29 | def left(self, x, y): 30 | if x < 0.5: 31 | return [self.size - 1, y] 32 | else: 33 | return [x - 1, y] 34 | 35 | def right(self, x, y): 36 | if x > self.size - 1.5: 37 | return [0, y] 38 | else: 39 | return [x + 1, y] 40 | 41 | def up(self, x, y): 42 | if y < 0.5: 43 | return [x, self.size - 1] 44 | else: 45 | return [x, y - 1] 46 | 47 | def down(self, x, y): 48 | if y > self.size - 1.5: 49 | return [x, 0] 50 | else: 51 | return [x, y + 1] 52 | 53 | # Calculate energies and magnetizations 54 | 55 | def unitE(self, x, y): 56 | [leftx, lefty] = self.left(x, y) 57 | [rightx, righty] = self.right(x, y) 58 | [upx, upy] = self.up(x, y) 59 | [downx, downy] = self.down(x, y) 60 | return -self.Jfactor * self.canvas[x, y] * \ 61 | (self.canvas[leftx, lefty] + self.canvas[rightx, righty] + 62 | self.canvas[upx, upy] + self.canvas[downx, downy]) 63 | 64 | def deltaE(self, x, y): 65 | return -4 * self.unitE(x, y) 66 | 67 | def totalE(self): 68 | totalEnergy = 0 69 | for x in range(0, self.size): 70 | for y in range(0, self.size): 71 | totalEnergy = totalEnergy + self.unitE(x, y) 72 | return totalEnergy 73 | 74 | def totalM(self): 75 | return np.sum(self.canvas) 76 | 77 | def avrE(self): 78 | return self.totalE() / (self.size * self.size) 79 | 80 | def avrM(self): 81 | return self.totalM() / (self.size * self.size) 82 | 83 | # Single flip (Metropolis method) 84 | 85 | def singleFlip(self, temperature): 86 | """Single flip (Metropolis method)""" 87 | 88 | # Randomly pick a spin to flip 89 | 90 | x = np.random.randint(0, self.size) 91 | y = np.random.randint(0, self.size) 92 | 93 | # Metropolis acceptance rate 94 | 95 | dE = self.deltaE(x, y) 96 | 97 | if dE < 0: 98 | self.canvas[x, y] = -self.canvas[x, y] 99 | else: 100 | if np.random.rand() < np.exp(-dE / temperature): 101 | self.canvas[x, y] = -self.canvas[x, y] 102 | 103 | # Return cluster size 104 | 105 | return 1 106 | 107 | # Cluster flip (Wolff method) 108 | 109 | def clusterFlip(self, temperature): 110 | """Cluster flip (Wolff method)""" 111 | 112 | # Randomly pick a seed spin 113 | 114 | x = np.random.randint(0, self.size) 115 | y = np.random.randint(0, self.size) 116 | 117 | sign = self.canvas[x, y] 118 | P_add = 1 - np.exp(-2 * self.Jfactor / temperature) 119 | stack = [[x, y]] 120 | lable = np.ones([self.size, self.size], int) 121 | lable[x, y] = 0 122 | 123 | while len(stack) > 0.5: 124 | 125 | # While stack is not empty, pop and flip a spin 126 | 127 | [currentx, currenty] = stack.pop() 128 | self.canvas[currentx, currenty] = -sign 129 | 130 | # Append neighbor spins 131 | 132 | # Left neighbor 133 | 134 | [leftx, lefty] = self.left(currentx, currenty) 135 | 136 | if self.canvas[leftx, lefty] * sign > 0.5 and \ 137 | lable[leftx, lefty] and np.random.rand() < P_add: 138 | stack.append([leftx, lefty]) 139 | lable[leftx, lefty] = 0 140 | 141 | # Right neighbor 142 | 143 | [rightx, righty] = self.right(currentx, currenty) 144 | 145 | if self.canvas[rightx, righty] * sign > 0.5 and \ 146 | lable[rightx, righty] and np.random.rand() < P_add: 147 | stack.append([rightx, righty]) 148 | lable[rightx, righty] = 0 149 | 150 | # Up neighbor 151 | 152 | [upx, upy] = self.up(currentx, currenty) 153 | 154 | if self.canvas[upx, upy] * sign > 0.5 and \ 155 | lable[upx, upy] and np.random.rand() < P_add: 156 | stack.append([upx, upy]) 157 | lable[upx, upy] = 0 158 | 159 | # Down neighbor 160 | 161 | [downx, downy] = self.down(currentx, currenty) 162 | 163 | if self.canvas[downx, downy] * sign > 0.5 and \ 164 | lable[downx, downy] and np.random.rand() < P_add: 165 | stack.append([downx, downy]) 166 | lable[downx, downy] = 0 167 | 168 | # Return cluster size 169 | 170 | return self.size * self.size - sum(sum(lable)) 171 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Bill 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 2D-Ising-Model-Python 2 | 3 | ## Description 4 | 5 | Simulating 2D Ising model with Monte Carlo Method in Python 3. 6 | 7 | -Bill in Beijing 8 | 9 | ## Tutorial 10 | 11 | The program is used to simulate 2D Ising model with the primary application of Python 3. I use two methods: Single-spin-flip and cluster- flip dymanics to deal with this task. 12 | 13 | Before running the program, you should add all the files into the same path. You'd better run the program in main.py unless you want to improve my code. 14 | 15 | You can adjust paramaters in main.py simply by changing the default values. 16 | 17 | Enjoy your time with Ising and Python! Suggestions and adjustments (as well as STARs) are welcomed. 18 | 19 | A detailed introduction of Simulating 2D Ising Model is uploaded on ZHIHU. It is a Chinese version, [click here](https://zhuanlan.zhihu.com/p/42629484) to view. 20 | 21 | Note: You'll probably need numpy and matplotlib. 22 | 23 | Created Nov. 1, 2019 by Bill in Beijing 24 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | """ 2 | This file runs Ising simulation 3 | Created: Mar. 30, 2019 4 | Last Edited: Apr. 6, 2019 5 | By Bill 6 | """ 7 | 8 | import IsingGrid 9 | import matplotlib as mpl 10 | import matplotlib.pyplot as plt 11 | from copy import deepcopy 12 | 13 | 14 | # Fundamental parameters 15 | 16 | size = 100 17 | temperature = 1 18 | steps = 400 19 | interval = 100 20 | Jfactor = 0.5 21 | 22 | # Generate grid 23 | 24 | g = IsingGrid.Grid(size, Jfactor) 25 | g.randomize() 26 | 27 | # Animation parameters 28 | 29 | fig, ax = plt.subplots() 30 | data = [] 31 | 32 | # Simulation 33 | 34 | print("Simulation begins.") 35 | 36 | for step in range(steps): 37 | 38 | # Single/cluster Filp 39 | 40 | # clusterSize = g.singleFlip(temperature) 41 | clusterSize = g.clusterFlip(temperature) 42 | 43 | if (step + 1) % interval == 0: 44 | data.append(deepcopy(g.canvas)) 45 | 46 | if (step + 1) % (10 * interval) == 0: 47 | print("Step ", step + 1, "/", steps, ", Cluster size ", clusterSize, "/", size * size) 48 | 49 | print("Simulation completes.") 50 | 51 | # Animation 52 | 53 | print("Animation begins.") 54 | 55 | for frame in range(0, len(data)): 56 | ax.cla() 57 | ax.imshow(data[frame], cmap=mpl.cm.winter) 58 | ax.set_title("Step {}".format(frame * interval)) 59 | plt.pause(0.01) 60 | 61 | print("Animation completes.") 62 | --------------------------------------------------------------------------------