Q-value_iteration.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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 Q_value_iteration:
  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.e = 0.001 # threshold for convergence
  17. self.gamma = 0.9 # discount factor
  18. self.obs = env.obs_map() # position of obstacles
  19. self.lose = env.lose_map() # position of lose states
  20. self.name1 = "Q-value_iteration, e=" + str(self.e) \
  21. + ", gamma=" + str(self.gamma)
  22. self.name2 = "convergence of error"
  23. def iteration(self):
  24. """
  25. Q_value_iteration
  26. :return: converged Q table and policy
  27. """
  28. Q_table = {}
  29. policy = {}
  30. delta = sys.maxsize
  31. count = 0
  32. for i in range(env.x_range):
  33. for j in range(env.y_range):
  34. if (i, j) not in self.obs:
  35. Q_table[(i, j)] = [0, 0, 0, 0] # initialize Q_table
  36. while delta > self.e: # convergence condition
  37. count += 1
  38. x_value = 0
  39. for x in Q_table:
  40. if x not in x_Goal:
  41. for k in range(len(self.u_set)):
  42. [x_next, p_next] = motion_model.move_prob(x, self.u_set[k], self.obs)
  43. Q_value = self.cal_Q_value(x_next, p_next, Q_table)
  44. v_diff = abs(Q_table[x][k] - Q_value)
  45. Q_table[x][k] = Q_value
  46. if v_diff > 0:
  47. x_value = max(x_value, v_diff)
  48. delta = x_value
  49. for x in Q_table:
  50. if x not in x_Goal:
  51. policy[x] = np.argmax(Q_table[x])
  52. self.message(count)
  53. return Q_table, policy
  54. def cal_Q_value(self, x, p, table):
  55. """
  56. cal Q_value.
  57. :param x: next state vector
  58. :param p: probability of each state
  59. :param table: value table
  60. :return: Q-value
  61. """
  62. value = 0
  63. reward = env.get_reward(x, self.xG, self.lose) # get reward of next state
  64. for i in range(len(x)):
  65. value += p[i] * (reward[i] + self.gamma * max(table[x[i]]))
  66. return value
  67. def simulation(self, xI, xG, policy):
  68. """
  69. simulate a path using converged policy.
  70. :param xI: starting state
  71. :param xG: goal state
  72. :param policy: converged policy
  73. :return: simulation path
  74. """
  75. plt.figure(1) # path animation
  76. tools.show_map(xI, xG, self.obs, self.lose, self.name1) # show background
  77. x, path = xI, []
  78. while True:
  79. u = self.u_set[policy[x]]
  80. x_next = (x[0] + u[0], x[1] + u[1])
  81. if x_next in self.obs:
  82. print("Collision!") # collision: simulation failed
  83. else:
  84. x = x_next
  85. if x_next in xG:
  86. break
  87. else:
  88. tools.plot_dots(x) # each state in optimal path
  89. path.append(x)
  90. plt.show()
  91. return path
  92. def message(self, count):
  93. print("starting state: ", self.xI)
  94. print("goal states: ", self.xG)
  95. print("condition for convergence: ", self.e)
  96. print("discount factor: ", self.gamma)
  97. print("iteration times: ", count)
  98. if __name__ == '__main__':
  99. x_Start = (5, 5)
  100. x_Goal = [(49, 5), (49, 25)]
  101. QVI = Q_value_iteration(x_Start, x_Goal)
  102. [value_QVI, policy_QVI] = QVI.iteration()
  103. path_VI = QVI.simulation(x_Start, x_Goal, policy_QVI)