Q-value_iteration.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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) + ", gamma=" + str(self.gamma)
  21. self.name2 = "convergence of error"
  22. def iteration(self):
  23. Q_table = {}
  24. policy = {}
  25. delta = sys.maxsize
  26. for i in range(env.x_range):
  27. for j in range(env.y_range):
  28. if (i, j) not in self.obs:
  29. Q_table[(i, j)] = [0, 0, 0, 0]
  30. while delta > self.e:
  31. x_value = 0
  32. for x in Q_table:
  33. if x not in x_Goal:
  34. for k in range(len(self.u_set)):
  35. [x_next, p_next] = motion_model.move_prob(x, self.u_set[k], self.obs)
  36. Q_value = self.cal_Q_value(x_next, p_next, Q_table)
  37. v_diff = abs(Q_table[x][k] - Q_value)
  38. Q_table[x][k] = Q_value
  39. if v_diff > 0:
  40. x_value = max(x_value, v_diff)
  41. delta = x_value
  42. for x in Q_table:
  43. if x not in x_Goal:
  44. policy[x] = np.argmax(Q_table[x])
  45. return policy
  46. def simulation(self, xI, xG, policy):
  47. path = []
  48. x = xI
  49. while x not in xG:
  50. u = self.u_set[policy[x]]
  51. x_next = (x[0] + u[0], x[1] + u[1])
  52. if x_next not in self.obs:
  53. x = x_next
  54. path.append(x)
  55. path.pop()
  56. return path
  57. def animation(self, path):
  58. plt.figure(1)
  59. tools.show_map(self.xI, self.xG, self.obs, self.lose, self.name1)
  60. for x in path:
  61. tools.plot_dots(x)
  62. plt.show()
  63. def cal_Q_value(self, x, p, table):
  64. value = 0
  65. reward = self.get_reward(x)
  66. for i in range(len(x)):
  67. value += p[i] * (reward[i] + self.gamma * max(table[x[i]]))
  68. return value
  69. def get_reward(self, x_next):
  70. reward = []
  71. for x in x_next:
  72. if x in self.xG:
  73. reward.append(10)
  74. elif x in self.lose:
  75. reward.append(-10)
  76. else:
  77. reward.append(0)
  78. return reward
  79. if __name__ == '__main__':
  80. x_Start = (5, 5)
  81. x_Goal = [(49, 5), (49, 25)]
  82. QVI = Q_value_iteration(x_Start, x_Goal)
  83. policy_QVI = QVI.iteration()
  84. path_VI = QVI.simulation(x_Start, x_Goal, policy_QVI)
  85. QVI.animation(path_VI)