Created
October 28, 2013 18:04
-
-
Save PiotrZakrzewski/7201603 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
from numpy.random import random, choice, randint | |
from numpy import zeros, copyto | |
import matplotlib.pyplot as plt | |
plt.ion() | |
def main(): | |
args = arguments() | |
m = generate_matrix(args.N) | |
s = generate_spin_vector(args.N) | |
results = list() | |
current = H(m,s) | |
for i in range(args.steps): | |
candidate_s = flip_spins(s) | |
result = H(m,candidate_s ) | |
if current - result > args.T: | |
s = candidate_s | |
results.append(result) | |
current = result | |
else: | |
results.append(current) | |
make_plot(results) | |
def flip_spins(s): | |
candidate = zeros(len(s)) | |
copyto(candidate,s) | |
random_index = randint(0,len(s)) | |
candidate[random_index] *= -1 | |
return candidate | |
def arguments(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("N",help="number of guests at the party",type=int) | |
parser.add_argument("T",help="""Temperature - threshold in change of H which | |
has to be exceeded in order for proposed change in | |
vector S to be accepted""",type=float) | |
parser.add_argument("steps",help="number of iterations of the algorithm",type=int) | |
return parser.parse_args() | |
def generate_matrix(N): | |
m = zeros((N,N)) | |
for i in range(N): | |
for j in range(N): | |
m[i,j] = random() * choice([-1,1]) | |
return m | |
def generate_spin_vector(N): | |
s = zeros(N) | |
for i in range(N): | |
s[i] = choice([-1,1]) | |
return s | |
def H(m,s): | |
value = 0 | |
N = len(m) | |
for i in range(N): | |
for j in range(N): | |
if not i == j: | |
value += -1*( m[i,j]*s[i]*s[j]) | |
return value | |
def make_plot(results): | |
plt.figure() | |
plt.plot(range(len(results)),results,label="H") | |
plt.xlabel("step") | |
plt.ylabel("Frustration") | |
plt.legend() | |
plt.savefig("Frustration at the party.png") | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment