Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random as rd
- import numpy as np
- import scipy as sp
- class TrafficSimulation():
- def __init__(self,road_length, traffic_density, vmax, p):
- self.road_length = length
- self.traffic_density = density
- self.vmax = vmax #maximum velocity
- self.v = v #velocity
- self.p = p #probability of slowing down
- time = 0
- global time, freeway, nextfreeway
- freeway = np.ones(length) * -2
- # to separate the empty cell and the occupied cell
- for i in range(length):
- loc = np.where(freeway = -2)[0]
- # the location of cars
- if rd.random() > density:
- freeway[i] = -1
- elif loc[i] - loc[i-1] > vmax:
- #compare number of empty cells with the max velocity
- freeway[i] = vmax
- else:
- freeway[i] = loc[i] - loc[i-1]
- nextfreeway = np.ones(length) * -1
- #set all to -1
- def move():
- for i in range(number_of_cars):
- iloc = np.where(freeway>-1)[0]
- time += 1
- if v == vmax and v < iloc[i] - iloc[i-1]:
- freeway[i+iloc[i]-iloc[-1] = vmax
- elif v <vmax and v < iloc[i] - iloc[i-1]:
- freeway[i+iloc[i]-iloc[-1] = v + 1
- elif v > iloc[i] - iloc[i-1]:
- freeway[i+iloc[i]-iloc[-1] = v - 1
- #update the location and space in three scenarios
- def display(self):
- print(''.join('.' if x == -1 else str(x) for x in self.state)
- simulation1 = TrafficSimulation(100,0.03,5, 0.5)
- simulation1.__init__()
- for i in range(10):
- simulation1.move()
- simulation1.display()
- simulation2 = TrafficSimulation(100,0.1,5, 0.5)
- simulation2.__init__()
- for i in range(10):
- simulation2.move()
- simulation2.display()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement