Created
July 2, 2018 15:30
-
-
Save ruliana/846640305c472f9688e669fa3cfe236a to your computer and use it in GitHub Desktop.
Nagel-Schreckenberg Traffic Simulation Cellular Automata
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 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