Sarsa.py 5.0 KB

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