Q-learning.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. import env
  2. import plotting
  3. import motion_model
  4. import numpy as np
  5. class QLEARNING:
  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 = "SARSA, 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. while x != xG: # stop condition
  33. u = self.epsilon_greedy(int(np.argmax(Q_table[x])), self.epsilon) # epsilon_greedy policy
  34. x_next = self.move_next(x, self.u_set[u]) # next state
  35. reward = self.env.get_reward(x_next) # reward observed
  36. Q_table[x][u] = (1 - self.alpha) * Q_table[x][u] + \
  37. self.alpha * (reward + self.gamma * max(Q_table[x_next]))
  38. x = x_next
  39. for x in Q_table:
  40. policy[x] = int(np.argmax(Q_table[x])) # extract policy
  41. return Q_table, policy
  42. def table_init(self):
  43. """
  44. Initialize Q_table: Q(s, a)
  45. :return: Q_table
  46. """
  47. Q_table = {}
  48. for x in self.stateSpace:
  49. u = []
  50. if x not in self.obs:
  51. for k in range(len(self.u_set)):
  52. if x == self.xG:
  53. u.append(0)
  54. else:
  55. u.append(np.random.random_sample())
  56. Q_table[x] = u
  57. return Q_table
  58. def state_init(self):
  59. """
  60. initialize a starting state
  61. :return: starting state
  62. """
  63. while True:
  64. i = np.random.randint(0, self.env.x_range - 1)
  65. j = np.random.randint(0, self.env.y_range - 1)
  66. if (i, j) not in self.obs:
  67. return (i, j)
  68. def epsilon_greedy(self, u, error):
  69. """
  70. generate a policy using epsilon_greedy algorithm
  71. :param u: original input
  72. :param error: epsilon value
  73. :return: epsilon policy
  74. """
  75. if np.random.random_sample() < 3 / 4 * error:
  76. u_e = u
  77. while u_e == u:
  78. p = np.random.random_sample()
  79. if p < 0.25:
  80. u_e = 0
  81. elif p < 0.5:
  82. u_e = 1
  83. elif p < 0.75:
  84. u_e = 2
  85. else:
  86. u_e = 3
  87. return u_e
  88. return u
  89. def move_next(self, x, u):
  90. """
  91. get next state.
  92. :param x: current state
  93. :param u: input
  94. :return: next state
  95. """
  96. x_next = (x[0] + u[0], x[1] + u[1])
  97. if x_next in self.obs:
  98. return x
  99. return x_next
  100. def extract_path(self, xI, xG, policy):
  101. """
  102. extract path from converged policy.
  103. :param xI: starting state
  104. :param xG: goal states
  105. :param policy: converged policy
  106. :return: path
  107. """
  108. x, path = xI, [xI]
  109. while x != xG:
  110. u = self.u_set[policy[x]]
  111. x_next = (x[0] + u[0], x[1] + u[1])
  112. if x_next in self.obs:
  113. print("Collision! Please run again!")
  114. break
  115. else:
  116. path.append(x_next)
  117. x = x_next
  118. return path
  119. def message(self):
  120. """
  121. print important message.
  122. :param count: iteration numbers
  123. :return: print
  124. """
  125. print("starting state: ", self.xI)
  126. print("goal state: ", self.xG)
  127. print("iteration numbers: ", self.M)
  128. print("discount factor: ", self.gamma)
  129. print("epsilon error: ", self.epsilon)
  130. print("alpha: ", self.alpha)
  131. if __name__ == '__main__':
  132. x_Start = (1, 1)
  133. x_Goal = (12, 1)
  134. Q_CALL = QLEARNING(x_Start, x_Goal)