Skip to content

Instantly share code, notes, and snippets.

@RyanGreenup
Created March 22, 2021 05:31
Show Gist options
  • Save RyanGreenup/420b604ec81e008aecb5c4b78aada634 to your computer and use it in GitHub Desktop.
Save RyanGreenup/420b604ec81e008aecb5c4b78aada634 to your computer and use it in GitHub Desktop.
Shelling Simulation in Julia
# using PyPlot
using GR
using ColorSchemes
N = 2000
try
mkdir("~/Sync/Documents/tmp/gifs")
catch
end
function main()
# Set Parameters
# TODO Fix non-square errors
# TODO Allow for 3 different factor types
width = 2000
height = 2000
# Initialise the Array
pic_mat = zeros(width, height)
fill_noise(pic_mat)
# Apply the Shelling Model N times
print("|--------------------------------------------------|\n")
for i in 1:N
shelling(pic_mat, width, height, 4)
# Display the plot
GR.setcolormap(47)
name = string("/home/ryan/Sync/Documents/tmp/gifs/j", lpad(i, 5, "0"), ".png")
pic = GR.imshow(pic_mat, color = "blue")
GR.savefig(name)
print(i*100/N, " % \n")
# TODO fix the loading bar
# Print the loading bar
# if ((i % (N/50)) == 0)
# print("#")
# end
end
# pic = PyPlot.imshow(pic_mat,interpolation="none")
#PyPlot.savefig("/tmp/pyplot.tiff", dpi = 999)
# PyPlot.display_figs()
end
function shelling(mat, width, height, t)
# Ignore the boundaries so (2:N-1)
for i in 2:(size(mat)[1]-1)
for j in 2:(size(mat)[2]-1)
# If not satisfied swap
if !satisfied_nb(mat, i, j, t)
j_new = rand(1:width)
i_new = rand(1:height)
# Maybe he has a change of heart
# mat[i, j] = rand(0:1)
new = mat[i_new, j_new]
old = mat[i, j]
mat[i, j] = new
mat[i_new, j_new] = old
# mat[i, j], mat[i_new, j_new] = mat[i_new, j_new], mat[i, j]
end
end
end
return mat
end
function satisfied_nb(mat, i, j, t)
like_neighbours = -1 # Don't count self
# Loop over the neighbours and count the number of
# similar neighbours
for y in (i-1):(i+1)
for x in (j-1):(j+1)
if (mat[i, j] == mat[x, y])
like_neighbours += 1
end
end
end
if like_neighbours >= t
return true
else
return false
end
end
function fill_noise(mat)
for i in 1:size(mat)[1]
for j in 1:size(mat)[2]
if rand([1,0])==1
mat[i, j] = 1
else
mat[i,j] = 0
end
end
end
end
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment