Sarsa.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @author: huiming zhou
  5. """
  6. import env
  7. import tools
  8. import motion_model
  9. import matplotlib.pyplot as plt
  10. import numpy as np
  11. import sys
  12. class SARSA:
  13. def __init__(self, x_start, x_goal):
  14. self.u_set = motion_model.motions # feasible input set
  15. self.xI, self.xG = x_start, x_goal
  16. self.M = 500
  17. self.gamma = 0.9 # discount factor
  18. self.alpha = 0.5
  19. self.epsilon = 0.1
  20. self.obs = env.obs_map() # position of obstacles
  21. self.lose = env.lose_map() # position of lose states
  22. self.name1 = "SARSA, M=" + str(self.M)
  23. self.name2 = "convergence of error"
  24. def Monte_Carlo(self):
  25. """
  26. Monte_Carlo experiments
  27. :return: Q_table, policy
  28. """
  29. Q_table = self.table_init()
  30. policy = {}
  31. count = 0
  32. for k in range(self.M):
  33. count += 1
  34. x = self.state_init()
  35. u = self.epsilon_greedy(int(np.argmax(Q_table[x])), self.epsilon)
  36. while x != self.xG:
  37. x_next = self.move_next(x, self.u_set[u])
  38. reward = env.get_reward(x_next, self.lose)
  39. u_next = self.epsilon_greedy(int(np.argmax(Q_table[x_next])), self.epsilon)
  40. Q_table[x][u] = (1 - self.alpha) * Q_table[x][u] + \
  41. self.alpha * (reward + self.gamma * Q_table[x_next][u_next])
  42. x, u = x_next, u_next
  43. for x in Q_table:
  44. policy[x] = int(np.argmax(Q_table[x]))
  45. return Q_table, policy
  46. def table_init(self):
  47. """
  48. Initialize Q_table: Q(s, a)
  49. :return: Q_table
  50. """
  51. Q_table = {}
  52. for i in range(env.x_range):
  53. for j in range(env.y_range):
  54. u = []
  55. if (i, j) not in self.obs:
  56. for k in range(len(self.u_set)):
  57. if (i, j) == self.xG:
  58. u.append(0)
  59. else:
  60. u.append(np.random.random_sample())
  61. Q_table[(i, j)] = u
  62. return Q_table
  63. def state_init(self):
  64. """
  65. initialize a starting state
  66. :return: starting state
  67. """
  68. while True:
  69. i = np.random.randint(0, env.x_range - 1)
  70. j = np.random.randint(0, env.y_range - 1)
  71. if (i, j) not in self.obs:
  72. return (i, j)
  73. def epsilon_greedy(self, u, error):
  74. """
  75. generate a policy using epsilon_greedy algorithm
  76. :param u: original input
  77. :param error: epsilon value
  78. :return: epsilon policy
  79. """
  80. if np.random.random_sample() < 3 / 4 * error:
  81. u_e = u
  82. while u_e == u:
  83. p = np.random.random_sample()
  84. if p < 0.25: u_e = 0
  85. elif p < 0.5: u_e = 1
  86. elif p < 0.75: u_e = 2
  87. else: 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 simulation(self, xI, xG, policy):
  102. """
  103. simulate a path using converged policy.
  104. :param xI: starting state
  105. :param xG: goal state
  106. :param policy: converged policy
  107. :return: simulation path
  108. """
  109. plt.figure(1) # path animation
  110. tools.show_map(xI, xG, self.obs, self.lose, self.name1) # show background
  111. x, path = xI, []
  112. while True:
  113. u = self.u_set[policy[x]]
  114. x_next = (x[0] + u[0], x[1] + u[1])
  115. if x_next in self.obs:
  116. print("Collision!") # collision: simulation failed
  117. else:
  118. x = x_next
  119. if x_next == xG:
  120. break
  121. else:
  122. tools.plot_dots(x) # each state in optimal path
  123. path.append(x)
  124. plt.show()
  125. return path
  126. if __name__ == '__main__':
  127. x_Start = (1, 1)
  128. x_Goal = (12, 1)
  129. SARSA_CALL = SARSA(x_Start, x_Goal)
  130. [value_SARSA, policy_SARSA] = SARSA_CALL.Monte_Carlo()
  131. path_VI = SARSA_CALL.simulation(x_Start, x_Goal, policy_SARSA)