Sarsa.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import env
  2. import plotting
  3. import motion_model
  4. import numpy as np
  5. class SARSA:
  6. def __init__(self, x_start, x_goal):
  7. self.xI, self.xG = x_start, x_goal
  8. self.M = 500 # iteration numbers
  9. self.gamma = 0.9 # discount factor
  10. self.alpha = 0.5
  11. self.epsilon = 0.1
  12. self.env = env.Env(self.xI, self.xG)
  13. self.motion = motion_model.Motion_model(self.xI, self.xG)
  14. self.plotting = plotting.Plotting(self.xI, self.xG)
  15. self.u_set = self.env.motions # feasible input set
  16. self.stateSpace = self.env.stateSpace # state space
  17. self.obs = self.env.obs_map() # position of obstacles
  18. self.lose = self.env.lose_map() # position of lose states
  19. self.name1 = "Q-learning, M=" + str(self.M)
  20. [self.value, self.policy] = self.Monte_Carlo(self.xI, self.xG)
  21. self.path = self.extract_path(self.xI, self.xG, self.policy)
  22. self.plotting.animation(self.path, self.name1)
  23. def Monte_Carlo(self, xI, xG):
  24. """
  25. Monte_Carlo experiments
  26. :return: Q_table, policy
  27. """
  28. Q_table = self.table_init() # Q_table initialization
  29. policy = {} # policy table
  30. for k in range(self.M): # iterations
  31. x = self.state_init() # initial state
  32. u = self.epsilon_greedy(int(np.argmax(Q_table[x])), self.epsilon)
  33. while x != xG: # stop condition
  34. x_next = self.move_next(x, self.u_set[u]) # next state
  35. reward = self.env.get_reward(x_next) # reward observed
  36. u_next = self.epsilon_greedy(int(np.argmax(Q_table[x_next])), self.epsilon)
  37. Q_table[x][u] = (1 - self.alpha) * Q_table[x][u] + \
  38. self.alpha * (reward + self.gamma * Q_table[x_next][u_next])
  39. x, u = x_next, u_next
  40. for x in Q_table:
  41. policy[x] = int(np.argmax(Q_table[x])) # extract policy
  42. return Q_table, policy
  43. def table_init(self):
  44. """
  45. Initialize Q_table: Q(s, a)
  46. :return: Q_table
  47. """
  48. Q_table = {}
  49. for x in self.stateSpace:
  50. u = []
  51. if x not in self.obs:
  52. for k in range(len(self.u_set)):
  53. if x == self.xG:
  54. u.append(0)
  55. else:
  56. u.append(np.random.random_sample())
  57. Q_table[x] = u
  58. return Q_table
  59. def state_init(self):
  60. """
  61. initialize a starting state
  62. :return: starting state
  63. """
  64. while True:
  65. i = np.random.randint(0, self.env.x_range - 1)
  66. j = np.random.randint(0, self.env.y_range - 1)
  67. if (i, j) not in self.obs:
  68. return (i, j)
  69. def epsilon_greedy(self, u, error):
  70. """
  71. generate a policy using epsilon_greedy algorithm
  72. :param u: original input
  73. :param error: epsilon value
  74. :return: epsilon policy
  75. """
  76. if np.random.random_sample() < 3 / 4 * error:
  77. u_e = u
  78. while u_e == u:
  79. p = np.random.random_sample()
  80. if p < 0.25:
  81. u_e = 0
  82. elif p < 0.5:
  83. u_e = 1
  84. elif p < 0.75:
  85. u_e = 2
  86. else:
  87. u_e = 3
  88. return u_e
  89. return u
  90. def move_next(self, x, u):
  91. """
  92. get next state.
  93. :param x: current state
  94. :param u: input
  95. :return: next state
  96. """
  97. x_next = (x[0] + u[0], x[1] + u[1])
  98. if x_next in self.obs:
  99. return x
  100. return x_next
  101. def extract_path(self, xI, xG, policy):
  102. """
  103. extract path from converged policy.
  104. :param xI: starting state
  105. :param xG: goal states
  106. :param policy: converged policy
  107. :return: path
  108. """
  109. x, path = xI, [xI]
  110. while x != xG:
  111. u = self.u_set[policy[x]]
  112. x_next = (x[0] + u[0], x[1] + u[1])
  113. if x_next in self.obs:
  114. print("Collision! Please run again!")
  115. return path
  116. else:
  117. path.append(x_next)
  118. x = x_next
  119. return path
  120. def message(self):
  121. """
  122. print important message.
  123. :param count: iteration numbers
  124. :return: print
  125. """
  126. print("starting state: ", self.xI)
  127. print("goal state: ", self.xG)
  128. print("iteration numbers: ", self.M)
  129. print("discount factor: ", self.gamma)
  130. print("epsilon error: ", self.epsilon)
  131. print("alpha: ", self.alpha)
  132. if __name__ == '__main__':
  133. x_Start = (1, 1)
  134. x_Goal = (12, 1)
  135. SARSA_CALL = SARSA(x_Start, x_Goal)