-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMDP.py
166 lines (144 loc) · 6.44 KB
/
MDP.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import numpy as np
import argparse
from math import fabs
class GridMDP:
def __init__(self, reward_matrix, init_state, action_list, terminal_states, gamma = 0.9):
self.reward_matrix = reward_matrix
self.init_state = init_state
self.action_list = action_list
self.terminal_states = terminal_states
self.gamma = gamma
def move(self, state, action):
"""Given a state and an action, return the new state"""
dimensions = self.reward_matrix.shape
next = list(state) #convert to list so it is mutable
if state in self.terminal_states: #Do nothing if we are in a terminal state
pass
#Check boundary conditions for each action case
#If action takes us out of boundary, return unchanged variable state
elif action == "L" and (state[1] > 0 and self.reward_matrix[state[0]][state[1]-1] != None):
next[1] -= 1
elif action == "R" and (state[1] < dimensions[1] - 1 and self.reward_matrix[state[0]][state[1]+1] != None):
next[1] += 1
elif action == "U" and (state[0] > 0 and self.reward_matrix[state[0] - 1][state[1]] != None):
next[0] -= 1
elif action == "D" and (state[0] < dimensions[0] - 1 and self.reward_matrix[state[0] + 1][state[1]] != None):
next[0] += 1
return tuple(next)
def possibleStates(self, state, action):
"""Given a state and action, returns a dict of possible final states along with their probabilities.
Example : possibleStates((2,3), U) = {(1,3) : 0.8
(2,2) : 0.1
(2,3) : 0.1}
"""
d = dict()
if action == 'L':
if self.move(state, 'L') in d:
d[self.move(state, 'L')] += 0.8
else:
d[self.move(state, 'L')] = 0.8
if self.move(state, 'U') in d:
d[self.move(state, 'U')] += 0.1
else:
d[self.move(state, 'U')] = 0.1
if self.move(state, 'D') in d:
d[self.move(state, 'D')] += 0.1
else:
d[self.move(state, 'D')] = 0.1
elif action == 'R':
if self.move(state, 'R') in d:
d[self.move(state, 'R')] += 0.8
else:
d[self.move(state, 'R')] = 0.8
if self.move(state, 'U') in d:
d[self.move(state, 'U')] += 0.1
else:
d[self.move(state, 'U')] = 0.1
if self.move(state, 'D') in d:
d[self.move(state, 'D')] += 0.1
else:
d[self.move(state, 'D')] = 0.1
elif action == 'U':
if self.move(state, 'U') in d:
d[self.move(state, 'U')] += 0.8
else:
d[self.move(state, 'U')] = 0.8
if self.move(state, 'L') in d:
d[self.move(state, 'L')] += 0.1
else:
d[self.move(state, 'L')] = 0.1
if self.move(state, 'R') in d:
d[self.move(state, 'R')] += 0.1
else:
d[self.move(state, 'R')] = 0.1
elif action == 'D':
if self.move(state, 'D') in d:
d[self.move(state, 'D')] += 0.8
else:
d[self.move(state, 'D')] = 0.8
if self.move(state, 'L') in d:
d[self.move(state, 'L')] += 0.1
else:
d[self.move(state, 'L')] = 0.1
if self.move(state, 'R') in d:
d[self.move(state, 'R')] += 0.1
else:
d[self.move(state, 'R')] = 0.1
return d
def transition(self, state1, action, state2):
return self.possibleStates(state1, action)[state2]
def value_iteration(MDP, epsilon = 0.001):
gamma = MDP.gamma
U1 = np.zeros(MDP.reward_matrix.shape) #initialise all utilities to 0
PolicyMatrix = np.chararray(MDP.reward_matrix.shape)
for terminal_state in MDP.terminal_states: # loop over all terminal states
U1[terminal_state[0]][terminal_state[1]] = MDP.reward_matrix[terminal_state[0]][terminal_state[1]] # set the end state utilities
PolicyMatrix[terminal_state[0]][terminal_state[1]] = 'X'
num_iters = 0
while True:
U2 = U1.copy()
delta = 0
#print U2
#print "ITERATION : ", num_iters
#raw_input("WAITING")
for i in range(len(MDP.reward_matrix)):
for j in range(len(MDP.reward_matrix[i])):
state = (i, j)
if state == (0,3) or state == (1, 3):
continue
if MDP.reward_matrix[i][j] is None:
continue
totalSum = {}
action_sum = 0
for action in MDP.action_list:
action_sum = 0
for possibleState, prob in MDP.possibleStates(state, action).items():
action_sum += prob * U2[possibleState[0]][possibleState[1]]
totalSum[action_sum] = action
delayed_reward = max(totalSum.keys())
policy = totalSum[delayed_reward]
U1[i][j] = MDP.reward_matrix[i][j] + MDP.gamma * delayed_reward
PolicyMatrix[i][j] = policy
delta = fabs(U2[state[0]][state[1]] - U1[state[0]][state[1]])
num_iters += 1
PolicyMatrix[1][1] = 'O'
for terminal_state in MDP.terminal_states: # loop over all terminal states
PolicyMatrix[terminal_state[0]][terminal_state[1]] = 'X'
if delta <= epsilon * (1 - gamma) / gamma:
return (U2, PolicyMatrix)
ap = argparse.ArgumentParser()
ap.add_argument("-r", "--reward", required = True)
args = vars(ap.parse_args())
reward = float(args["reward"])
reward_matrix = np.array([[reward, reward, reward, 1],
[reward, None, reward, -1],
[reward, reward, reward, reward]])
init_state = (2,0)
action_list = ['L', 'R', 'U', 'D']
terminal_states = [(0,3), (1,3)]
MDPProblem = GridMDP(reward_matrix, init_state, action_list, terminal_states, 1)
UtilityMatrix, PolicyMatrix = value_iteration(MDPProblem, 0.001)
print "Utility Matrix : "
print UtilityMatrix
print "Optimal Policies :"
print PolicyMatrix