Skip to content

Instantly share code, notes, and snippets.

@dela3499
Last active March 6, 2016 13:11
Show Gist options
  • Save dela3499/d9a67936fd39c0227ca3 to your computer and use it in GitHub Desktop.
Save dela3499/d9a67936fd39c0227ca3 to your computer and use it in GitHub Desktop.
Trace text with Langton ant
execfile('viridis.py')
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
from PIL import Image
def image2array(filename):
im = Image.open('logo.jpg')
return np.array(im.convert('L')) > 100
def getEdgePoints(array):
n = array.shape[0]
rows = np.array(np.repeat(np.matrix(np.arange(1, n + 1)).T, n, axis = 1))
cols = np.array(np.repeat(np.matrix(np.arange(1, n + 1)), n, axis = 0))
horizontaledges = np.hstack([array[:,:-1] - array[:,1:], np.zeros((n,1))]) != 0
verticaledges = np.hstack([(array.T[:,:-1] - array.T[:,1:]), np.zeros((n,1))]).T != 0
edges = horizontaledges | verticaledges
rowi = rows[edges].flatten().tolist()
coli = cols[edges].flatten().tolist()
return zip(rowi, coli)
def updatePosition(position, direction):
movement = [(1,0), (0,1), (-1, 0), (0, -1)] # up, down, right, left, like a clock
return tuple(np.array(position) + np.array(movement[direction]))
# Model -> Model
def update(model):
newPosition = updatePosition(model['position'], model['direction'])
model['path'][newPosition] += 1
x,y = newPosition
n = model['grid'].shape[0]
model['position'] = (x % (n - 1), y % (n - 1))
currentValue = model['grid'][newPosition]
if currentValue == 0:
model['direction'] = (model['direction'] + 1) % 4
model['grid'][newPosition] = 1
else:
model['direction'] = (model['direction'] - 1) % 4
model['grid'][newPosition] = 0
return model
def sample(x, nSamples):
n = len(x)
return map(lambda x: x[1], sorted(zip(np.random.random(n), x), key = lambda x: x[0]))[:nSamples]
n = 1000
offset = int(n / 2.0)
iters = int(3e4) #int(3e7) # Took 8 min. to compute
im = image2array('logo.jpg')
rand = np.random.random((n, n)) > 0.1
mat = im & rand
nPoints = 1000
startingPoints = sample(getEdgePoints(im), nPoints) #(np.random.random((nPoints, 2)) * 1000).astype(int).tolist()
paths = []
for point in startingPoints:
initialModel = {
"grid": mat.copy(),
"position": point,
"direction": 0,
"path": np.zeros((n, n))
}
for i in xrange(iters):
initialModel = update(initialModel)
paths.append(initialModel['path'])
plt.figure(figsize = (50,50)) # High resolution (takes a while)
plt.imshow(
sum(paths) - im * 10,
cmap = 'Greys_r',
interpolation = 'nearest',
vmax = 500)
plt.axis("off")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment