Skip to content

Instantly share code, notes, and snippets.

@profConradi
Last active August 28, 2024 18:46
Show Gist options
  • Save profConradi/4dba7ed5bec5fd7e20aa95a092456ad1 to your computer and use it in GitHub Desktop.
Save profConradi/4dba7ed5bec5fd7e20aa95a092456ad1 to your computer and use it in GitHub Desktop.
Nils Aall Barricelli cellular automata provisional code
import numpy as np
from numba import njit
@njit
def evolve(initial_row, time):
size = initial_row.shape[0]
world = np.zeros((time, size), dtype = np.int8)
world[0] = initial_row
for t in range(1, time):
world_after_movements = np.zeros(size, dtype = np.int8)
collisions = -1*np.ones(size, dtype = np.int8)
#movements and collisions
for pos, n in enumerate(world[t-1]):
if n!=0:
next_position = (pos + n)%size
world_after_movements[next_position] = n
collisions[next_position] += 1
world_after_movements[collisions>0] = 0
#mutation
for pos, c in enumerate(collisions):
if (c>0) and (world[t-1,pos]) == 0:
closest_right = 0
closest_right_d = 0
for i in range(pos+1, size):
if world[t-1,i]!=0:
closest_right = world[t-1,i]
closest_right_d = i-pos
break
closest_left = 0
closest_left_d = 0
for i in range(pos-1, -1, -1):
if world[t-1,i]!=0:
closest_left = world[t-1,i]
closest_left_d = pos-i
break
sig = np.sign(closest_left*closest_right)
val = min(closest_left_d,closest_right_d)
world_after_movements[pos] = sig*val
#reproduction
world_after_reproduction = world_after_movements.copy()
children = np.zeros(size, dtype = np.int8)
birth = np.zeros(size, dtype = np.int8)
for pos, n in enumerate(world_after_movements):
if (n!=0) and (world[t-1,pos] != 0):
next_position = (pos - n + world[t-1,pos])%size
birth[next_position] += 1
children[next_position] = n
valid_birth = (birth == 1) & (world_after_reproduction == 0)
world_after_reproduction[valid_birth] = children[valid_birth]
world[t] = world_after_reproduction.copy()
return world
size=1000
time=1000
max_number = 5
ir = np.random.choice(np.arange(-max_number,max_number+1), size)
world = evolve(ir, time)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment