Skip to content

Instantly share code, notes, and snippets.

@ruliana
Created July 2, 2018 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruliana/846640305c472f9688e669fa3cfe236a to your computer and use it in GitHub Desktop.
Save ruliana/846640305c472f9688e669fa3cfe236a to your computer and use it in GitHub Desktop.
Nagel-Schreckenberg Traffic Simulation Cellular Automata
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from itertools import takewhile
from random import random
MAX_VELOCITY = 5
def space():
return " "
def is_space(n):
return n == space()
def step(source):
rslt = acceleration(source)
rslt = slowing_down(rslt)
rslt = randomize(rslt)
return move(rslt)
def acceleration(lane):
return [v + 1 if not is_space(v) and v < MAX_VELOCITY else v
for v in lane]
def slowing_down(lane):
rslt = []
extended_lane = lane + lane
for i, v in enumerate(lane):
if is_space(v):
rslt.append(v)
else:
space_ahead = list(takewhile(is_space, extended_lane[i + 1:]))
new_velocity = min(v, len(space_ahead))
rslt.append(new_velocity)
return rslt
def randomize(lane):
return [v - 1 if not is_space(v) and v >= 1 and random() < 0.1 else v
for v in lane]
def move(lane):
lane_size = len(lane)
rslt = [space()] * lane_size
for i, v in enumerate(lane):
if is_space(v): continue
rslt[(i + v) % lane_size] = v
return rslt
#%%
lane = [space(), space(), 1, space(), 1, 1, space(), space()]
print(lane)
for _ in range(50):
lane = step(lane)
print(lane)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment