value_iteration.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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 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 = "value_iteration, e=" + str(self.e) \
  21. + ", gamma=" + str(self.gamma)
  22. self.name2 = "convergence of error, e=" + str(self.e)
  23. def iteration(self):
  24. """
  25. value_iteration.
  26. :return: converged value table, optimal policy and variation of difference,
  27. """
  28. value_table = {} # value table
  29. policy = {} # policy
  30. diff = [] # maximum difference between two successive iteration
  31. delta = sys.maxsize # initialize maximum difference
  32. count = 0 # iteration times
  33. for i in range(env.x_range):
  34. for j in range(env.y_range):
  35. if (i, j) not in self.obs:
  36. value_table[(i, j)] = 0 # initialize value table for feasible states
  37. while delta > self.e: # converged condition
  38. count += 1
  39. x_value = 0
  40. for x in value_table:
  41. if x not in self.xG:
  42. value_list = []
  43. for u in self.u_set:
  44. [x_next, p_next] = motion_model.move_prob(x, u, self.obs) # recall motion model
  45. value_list.append(self.cal_Q_value(x_next, p_next, value_table)) # cal Q value
  46. policy[x] = self.u_set[int(np.argmax(value_list))] # update policy
  47. v_diff = abs(value_table[x] - max(value_list)) # maximum difference
  48. value_table[x] = max(value_list) # update value table
  49. if v_diff > 0:
  50. x_value = max(x_value, v_diff)
  51. delta = x_value # update delta
  52. diff.append(delta)
  53. self.message(count) # print key parameters
  54. return value_table, policy, diff
  55. def cal_Q_value(self, x, p, table):
  56. """
  57. cal Q_value.
  58. :param x: next state vector
  59. :param p: probability of each state
  60. :param table: value table
  61. :return: Q-value
  62. """
  63. value = 0
  64. reward = env.get_reward(x, self.xG, self.lose) # get reward of next state
  65. for i in range(len(x)):
  66. value += p[i] * (reward[i] + self.gamma * table[x[i]]) # cal Q-value
  67. return value
  68. def simulation(self, xI, xG, policy, diff):
  69. """
  70. simulate a path using converged policy.
  71. :param xI: starting state
  72. :param xG: goal state
  73. :param policy: converged policy
  74. :return: simulation path
  75. """
  76. plt.figure(1) # path animation
  77. tools.show_map(xI, xG, self.obs, self.lose, self.name1) # show background
  78. x, path = xI, []
  79. while True:
  80. u = policy[x]
  81. x_next = (x[0] + u[0], x[1] + u[1])
  82. if x_next in self.obs:
  83. print("Collision!") # collision: simulation failed
  84. else:
  85. x = x_next
  86. if x_next in xG: break
  87. else:
  88. tools.plot_dots(x) # each state in optimal path
  89. path.append(x)
  90. plt.pause(1)
  91. plt.figure(2) # difference between two successive iteration
  92. plt.plot(diff, color='#808080', marker='o')
  93. plt.title(self.name2, fontdict=None)
  94. plt.xlabel('iterations')
  95. plt.grid('on')
  96. plt.show()
  97. return path
  98. def message(self, count):
  99. print("starting state: ", self.xI)
  100. print("goal states: ", self.xG)
  101. print("condition for convergence: ", self.e)
  102. print("discount factor: ", self.gamma)
  103. print("iteration times: ", count)
  104. if __name__ == '__main__':
  105. x_Start = (5, 5) # starting state
  106. x_Goal = [(49, 5), (49, 25)] # goal states
  107. VI = Value_iteration(x_Start, x_Goal)
  108. [value_VI, policy_VI, diff_VI] = VI.iteration()
  109. path_VI = VI.simulation(x_Start, x_Goal, policy_VI, diff_VI)