Skip to content
Snippets Groups Projects
Commit 282a0cc4 authored by Bachir Lachguel's avatar Bachir Lachguel
Browse files

Implement nagel-schreckenberg

parent 30e36ed1
Branches
No related tags found
No related merge requests found
from random import uniform, shuffle
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
L = 500 # number of cells in row
num_iters = 500 # number of iterations
density = 0.48 # how many positives
vmax = 2
p = 0.2
cars_num = int(density * L)
initial = [0] * cars_num + [-1] * (L - cars_num)
shuffle(initial)
iterations = [initial]
for i in range(num_iters):
prev,curr = iterations[-1],[-1] * L
for x in range(L):
if prev[x] > -1:
vi = prev[x]
d = 1
while prev[(x + d) % L] < 0:
d += 1
vtemp = min(vi+1, d - 1, vmax) # increse speed up to max speed, but don't move further than next car
v = max(vtemp - 1, 0) if uniform(0,1) < p else vtemp # with probability p hit the brakes, otherwise sustain velocity
curr[(x + v) % L] = v # perform the move
#print(x,v)
iterations.append(curr)
a = np.zeros(shape=(num_iters,L))
for i in range(L):
for j in range(num_iters):
a[j,i] = 1 if iterations[j][i] > -1 else 0
# showing image
plt.imshow(a, cmap="Greys", interpolation="nearest")
plt.show()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment