I want to implement the Nagel-Schreckenberg model with CellularAutomaton in Mathematica. I saw some code for the traffic model. But what I want is the most basic Nagel-Schreckenberg model. I hope someone will give me the code.
Asked
Active
Viewed 611 times
3
C. E.
- 70,533
- 6
- 140
- 264
Wuyang Zhang
- 33
- 4
1 Answers
4
Here's my take on it. As far as I can tell, the type of rules that are involved in the Nagel-Schreckenberg model cannot be implemented with CellularAutomaton, so I had to resort to a different approach.
accelerate[map_] := Replace[
map,
speed_?NonNegative :> Min[5, speed + 1],
{1}
]
slow[map_] := Replace[
Partition[map, 6, 1, {1, 1}], {
{v_?NonNegative, empty : Longest[-1 ...], ___} :>
Min[v, Length[{empty}]],
{-1, ___} :> -1
},
{1}
]
slowRandom[map_, p_] := Replace[
map,
speed_?Positive :> RandomChoice[{1 - p, p} -> {speed, speed - 1}],
{1}
]
move[map_, n_] := Module[{pos},
pos = Position[Partition[map, n + 1, 1, {1, 1}], {n, -1 ..}];
ReplacePart[
map,
Join[Thread[pos -> -1], Thread[Mod[pos + n, Length[map], 1] -> n]]
]
]
iterate[map_, p_] := RightComposition[
accelerate,
slow,
slowRandom[#, p] &,
Fold[move, #, Range[5]] &
]@map
Here is how you can run a simulation with density 0.35 and $p=0.3$, like in that image on Wikipedia:
map = RandomChoice[{0.65, 0.35} -> {-1, 0}, 100];
data = NestList[iterate[#, 0.3] &, map, 100];
ArrayPlot[data, ColorRules -> {-1 -> White, _ -> Black}]

In this picture, empty cells are white, and cars are black.
If you found this interesting, you may also want to check out my implementation of the Levine-Middleton-Biham traffic model, another cellular automaton, here.
C. E.
- 70,533
- 6
- 140
- 264
-
I sincerely thank you, I will study this code well, I can not image that the first time I sent a question, someone will help me answer. Few people in China's domestic mathematica will help answer. – Wuyang Zhang Sep 04 '19 at 12:10
Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign!
– Carl Lange Aug 27 '19 at 10:17CellularAutomaton[184, {1,0,0,1,1,1,1,0,0,0}, 50](naturally, vary the initial condition and number of iterations to your heart's content) – Carl Lange Aug 27 '19 at 14:36CellularAutomaton(in Chinese here, if that's useful to you). This question may also be useful to you. Good luck! – Carl Lange Aug 28 '19 at 10:52