-
Notifications
You must be signed in to change notification settings - Fork 0
/
netIsingDriver.py
268 lines (233 loc) · 8.49 KB
/
netIsingDriver.py
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# =============================================================================
# Main Driver for Ising Model Applied to Networks
#
# Author: Max Graves
# Last Revised: 06-MAY-2013
# =============================================================================
import networkx as nx
import pylab as pl
import sys, random, argparse, os, subprocess, glob
# =============================================================================
def parseCMD():
"""
Parse the command line.
"""
parser = argparse.ArgumentParser(description = 'Ising Model for Networks')
parser.add_argument("-S", "--showHist", action="store_true",
dest="showHist", default=False,
help="show the simulation in histogram form (SLOW!)")
parser.add_argument("-E", "--evolve", action="store_true",
dest="evolve", default=False,
help="save images to disk of algorithm (for video)")
parser.add_argument("-A", "--align", action="store_true",
dest="align", default=False,
help="Start all spins in the up state")
parser.add_argument('--nodes', '-N', type=int, default=10,
help='number of nodes in network')
parser.add_argument('--temp', '-T', type=float, default = 5.0,
help='enter temperature in kelvin')
parser.add_argument('--field', '-H', type=float, default=0.0,
help='enter magnetic field strength')
parser.add_argument('--exchange', '-J', type=float, default=1,
help='enter the value of the exchange constant')
parser.add_argument('--sweeps', '-s', type=int, default = 2000,
help='enter the number of MC sweeps')
return parser.parse_args()
# =============================================================================
def findMencoder():
""" checks for Mencoder, returns error and exits if it doesn't find it """
try:
subprocess.check_call(['mencoder'])
except subprocess.CalledProcessError:
print "mencoder command was found"
pass
except OSError:
print 'could not find mencoder.'
sys.exit("quitting\n")
# =============================================================================
def swapSpin(spinUp, spinDown, spin, totSpin):
"""
Removes a node index from one list and puts it in the other.
"""
if spin in spinDown:
spinDown.remove(spin)
spinUp.append(spin)
totSpin += 2
else:
spinUp.remove(spin)
spinDown.append(spin)
totSpin -= 2
return spinUp, spinDown, totSpin
# =============================================================================
def EnergyChange(spinUp, G, J, R):
"""
calculates the energy change of flipping a spin.
"""
if R in spinUp:
tempSpin = 1.0
else:
tempSpin = -1.0
spinSum = 0.0
for i in G[R]:
spinSum += tempSpin*G[R][i]
delE = 2.0 * J * spinSum
return delE
# =============================================================================
def updatePlot(G, position, spinUp, spinDown, upColor, downColor, ax, E, step):
"""
Updates plot of network for viewing MC moves.
"""
pl.cla()
position = nx.circular_layout(G)
nx.draw_networkx_nodes(G,position, nodelist=spinUp,
node_color=upColor)
nx.draw_networkx_nodes(G,position, nodelist=spinDown,
node_color=downColor)
nx.draw_networkx_edges(G,position)
nx.draw_networkx_labels(G,position)
ax.text(-0.1, 0.98, 'Spin Up', style='italic',
bbox={'facecolor':upColor, 'alpha':0.9, 'pad':10})
ax.text(-0.1, 1.1, 'Spin Down', style='italic',color='White',
bbox={'facecolor':downColor, 'alpha':0.9, 'pad':10})
if E:
os.chdir('./data/')
if os.path.exists('./animate'):
pass
else:
os.mkdir('./animate/')
os.chdir('./animate/')
pl.savefig('animate_'+str(step)+'.png')
os.chdir('../..')
pl.draw()
# =============================================================================
def main():
# assign variables, define constants
args = parseCMD()
T,H,N = float(args.temp), float(args.field), int(args.nodes)
J, s = float(args.exchange), int(args.sweeps)
k_B = 1 # = 1.3806503 * pow(10,-23)
upColor = 'Fuchsia'
downColor = 'Black'
if args.evolve:
findMencoder()
if args.align:
print 'Chose to start all spins in up position'
K = 3
m = 5
# http://networkx.github.com/documentation/latest/tutorial/
# tutorial.html#adding-attributes-to-graphs-nodes-and-edges
#G = nx.complete_graph(N)
#G = nx.karate_club_graph()
#z=[K for i in range(N)]
#G=nx.expected_degree_graph(z)
G = nx.barabasi_albert_graph(N, m, seed=None)
# keep track of spins of nodes
spinUp, spinDown = [], []
# assign each node a spin (\pm 1)
for node in G:
if args.align:
r = 1.0
else:
r = 2.0*random.randint(0,1)-1.0
if r == 1.0:
spinUp.append(node)
else:
spinDown.append(node)
for neighbor in range(len(G)):
if neighbor in G[node]:
G[neighbor][node] = r
else:
pass
# compute initial quantities
totSpin = len(spinUp) - len(spinDown)
spinSum = 0.0
for i in range(len(G)):
if i in spinUp:
tempSpin = 1.0
else:
tempSpin = -1.0
for j in G[i]:
spinSum += tempSpin*G[i][j]
E = - 0.5 * J * spinSum # divide by two because of double counting
M = 1.0*totSpin/(1.0*N)
# define arrays for mcSteps, Energies, Magnetism
mcSteps, Es, Ms = pl.arange(s), pl.array([E]), pl.array([M])
E2 = pl.array([E*E])
# keep track of acceptance
a = 0 # accepted moves
r = 0 # rejected moves
if args.showHist:
pl.ion()
fig = pl.figure(1)
ax = fig.add_subplot(111)
position = nx.circular_layout(G)
for step in mcSteps:
# randomly choose a node to try to flip the spin
R = random.randint(0,len(G)-1)
# compute change in energy from flipping that spin
delE = EnergyChange(spinUp, G, J, R)
# calculate Boltzmann factor
Boltz = pl.exp(-1.0*delE/(k_B*T))
if (delE <= 0):
reject = False
E += delE
spinUp, spinDown, totSpin = swapSpin(spinUp,
spinDown, R, totSpin)
else:
n = random.random()
if (n <= Boltz):
E += delE
reject = False
spinUp, spinDown, totSpin = swapSpin(spinUp,
spinDown, R, totSpin)
else:
reject = True
if reject==True:
r += 1
else:
a += 1
# calculate magnetism (not absolute value)
M = 1.0*totSpin/(1.0*N)
# store observables in array
Es = pl.append(Es, E)
Ms = pl.append(Ms, M)
E2 = pl.append(E2, E*E)
if args.showHist:
updatePlot(G, position, spinUp, spinDown, upColor, downColor, ax,
args.evolve, step)
if args.showHist:
pl.close()
pl.ioff()
if args.evolve:
os.chdir('./data/animate/')
# set up bash commands to run mencoder
command = ('mencoder', 'mf://*.png', '-mf', 'type=png:w=800:h=600:fps=25',
'-ovc', 'lavc', '-lavcopts', 'vcodec=mpeg4', '-oac', 'copy',
'-o', 'fightingNodes.avi')
print "\n\nabout to execute:\n%s\n\n" % ' '.join(command)
subprocess.check_call(command)
print os.getcwd()
for image in glob.glob('*png*'):
os.remove(image)
os.chdir('../..')
print "\n The movie was written to 'fightingNodes.avi'"
print 'acceptance ratio: ', 1.0*a/(r+a)
if os.path.exists('./data/'):
os.chdir('./data/')
else:
os.mkdir('./data/')
os.chdir('./data/')
filename = 'ising2D_L%s_s%s_Temp%s.dat'%(int(N), s, T)
fid = open(filename, 'w')
fid.write('# temp: %s\n'%T)
fid.write('# nodes: %s\n'%N)
fid.write('# field: %s\n'%H)
fid.write('# %15s\t%15s\t%15s\t%15s\n'%('mcSteps','Energies',
'Magnetism','Energy^2'))
zipped = zip(mcSteps, Es, Ms, E2)
pl.savetxt(fid, zipped, fmt='%5.9f\t%5.9f\t%5.9f\t%5.9f')
fid.close()
print 'Data has been saved to: ',filename
# =============================================================================
if __name__=='__main__':
main()