Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. import random as rd
  2. import numpy as np
  3. import scipy as sp
  4.  
  5. class TrafficSimulation():
  6. def __init__(self,road_length, traffic_density, vmax, p):
  7. self.road_length = length
  8. self.traffic_density = density
  9. self.vmax = vmax #maximum velocity
  10. self.v = v #velocity
  11. self.p = p #probability of slowing down
  12.  
  13. time = 0
  14. global time, freeway, nextfreeway
  15.  
  16. freeway = np.ones(length) * -2
  17. # to separate the empty cell and the occupied cell
  18. for i in range(length):
  19. loc = np.where(freeway = -2)[0]
  20. # the location of cars
  21. if rd.random() > density:
  22. freeway[i] = -1
  23. elif loc[i] - loc[i-1] > vmax:
  24. #compare number of empty cells with the max velocity
  25. freeway[i] = vmax
  26. else:
  27. freeway[i] = loc[i] - loc[i-1]
  28.  
  29. nextfreeway = np.ones(length) * -1
  30. #set all to -1
  31. def move():
  32. for i in range(number_of_cars):
  33. iloc = np.where(freeway>-1)[0]
  34. time += 1
  35. if v == vmax and v < iloc[i] - iloc[i-1]:
  36. freeway[i+iloc[i]-iloc[-1] = vmax
  37. elif v <vmax and v < iloc[i] - iloc[i-1]:
  38. freeway[i+iloc[i]-iloc[-1] = v + 1
  39. elif v > iloc[i] - iloc[i-1]:
  40. freeway[i+iloc[i]-iloc[-1] = v - 1
  41. #update the location and space in three scenarios
  42.  
  43. def display(self):
  44. print(''.join('.' if x == -1 else str(x) for x in self.state)
  45.  
  46.  
  47. simulation1 = TrafficSimulation(100,0.03,5, 0.5)
  48. simulation1.__init__()
  49. for i in range(10):
  50. simulation1.move()
  51. simulation1.display()
  52. simulation2 = TrafficSimulation(100,0.1,5, 0.5)
  53. simulation2.__init__()
  54. for i in range(10):
  55. simulation2.move()
  56. simulation2.display()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement