test_mdptoolbox.py 12.9 KB
Newer Older
Steven Cordwell's avatar
Steven Cordwell committed
1
2
3
4
5
6
7
# -*- coding: utf-8 -*-
"""
Created on Sun May 27 23:16:57 2012

@author: -
"""

Steven Cordwell's avatar
Steven Cordwell committed
8
from mdp import check, checkSquareStochastic, exampleForest, exampleRand, MDP
9
from mdp import PolicyIteration, ValueIteration, ValueIterationGS
Steven Cordwell's avatar
Steven Cordwell committed
10
11
12
13
from numpy import absolute, array, eye, matrix, zeros
from numpy.random import rand
from scipy.sparse import eye as speye
from scipy.sparse import csr_matrix as sparse
Steven Cordwell's avatar
Steven Cordwell committed
14
#from scipy.stats.distributions import poisson
Steven Cordwell's avatar
Steven Cordwell committed
15

Steven Cordwell's avatar
Steven Cordwell committed
16
17
STATES = 10
ACTIONS = 3
18
SMALLNUM = 10e-12
Steven Cordwell's avatar
Steven Cordwell committed
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

# check: square, stochastic and non-negative ndarrays

def test_check_square_stochastic_nonnegative_array_1():
    P = zeros((ACTIONS, STATES, STATES))
    R = zeros((STATES, ACTIONS))
    for a in range(ACTIONS):
        P[a, :, :] = eye(STATES)
        R[:, a] = rand(STATES)
    assert (check(P, R) == None)

def test_check_square_stochastic_nonnegative_array_2():
    P = zeros((ACTIONS, STATES, STATES))
    R = rand(ACTIONS, STATES, STATES)
    for a in range(ACTIONS):
        P[a, :, :] = eye(STATES)
    assert (check(P, R) == None)

# check: P - square, stochastic and non-negative object arrays

def test_check_P_square_stochastic_nonnegative_object_array():
    P = zeros((ACTIONS, ), dtype=object)
    R = rand(STATES, ACTIONS)
    for a in range(ACTIONS):
        P[a] = eye(STATES)
    assert (check(P, R) == None)

def test_check_P_square_stochastic_nonnegative_object_matrix():
    P = zeros((ACTIONS, ), dtype=object)
    R = rand(STATES, ACTIONS)
    for a in range(ACTIONS):
        P[a] = matrix(eye(STATES))
    assert (check(P, R) == None)

def test_check_P_square_stochastic_nonnegative_object_sparse():
    P = zeros((ACTIONS, ), dtype=object)
    R = rand(STATES, ACTIONS)
    for a in range(ACTIONS):
        P[a] = speye(STATES, STATES).tocsr()
    assert (check(P, R) == None)

# check: R - square stochastic and non-negative sparse

def test_check_R_square_stochastic_nonnegative_sparse():
    P = zeros((ACTIONS, STATES, STATES))
    R = sparse(rand(STATES, ACTIONS))
    for a in range(ACTIONS):
        P[a, :, :] = eye(STATES)
    assert (check(P, R) == None)

# check: R - square, stochastic and non-negative object arrays

def test_check_R_square_stochastic_nonnegative_object_array():
    P = zeros((ACTIONS, STATES, STATES))
    R = zeros((ACTIONS, ), dtype=object)
    for a in range(ACTIONS):
        P[a, :, :] = eye(STATES)
        R[a] = rand(STATES, STATES)
    assert (check(P, R) == None)

def test_check_R_square_stochastic_nonnegative_object_matrix():
    P = zeros((ACTIONS, STATES, STATES))
    R = zeros((ACTIONS, ), dtype=object)
    for a in range(ACTIONS):
        P[a, :, :] = eye(STATES)
        R[a] = matrix(rand(STATES, STATES))
    assert (check(P, R) == None)

def test_check_R_square_stochastic_nonnegative_object_sparse():
    P = zeros((ACTIONS, STATES, STATES))
    R = zeros((ACTIONS, ), dtype=object)
    for a in range(ACTIONS):
        P[a, :, :] = eye(STATES)
        R[a] = sparse(rand(STATES, STATES))
    assert (check(P, R) == None)

# checkSquareStochastic: square, stochastic and non-negative

def test_checkSquareStochastic_square_stochastic_nonnegative_array():
    P = rand(STATES, STATES)
    for s in range(STATES):
        P[s, :] = P[s, :] / P[s, :].sum()
    assert checkSquareStochastic(P) == None

def test_checkSquareStochastic_square_stochastic_nonnegative_matrix():
    P = rand(STATES, STATES)
    for s in range(STATES):
        P[s, :] = P[s, :] / P[s, :].sum()
    P = matrix(P)
    assert checkSquareStochastic(P) == None

def test_checkSquareStochastic_square_stochastic_nonnegative_sparse():
    P = rand(STATES, STATES)
    for s in range(STATES):
        P[s, :] = P[s, :] / P[s, :].sum()
    P = sparse(P)
    assert checkSquareStochastic(P) == None

# checkSquareStochastic: eye

def test_checkSquareStochastic_eye_array():
    P = eye(STATES)
    assert checkSquareStochastic(P) == None

def test_checkSquareStochastic_eye_matrix():
    P = matrix(eye(STATES))
    assert checkSquareStochastic(P) == None

def test_checkSquareStochastic_eye_sparse():
    P = speye(STATES, STATES).tocsr()
    assert checkSquareStochastic(P) == None
Steven Cordwell's avatar
Steven Cordwell committed
130

Steven Cordwell's avatar
Steven Cordwell committed
131
# exampleForest
132
Pf, Rf = exampleForest()
Steven Cordwell's avatar
Steven Cordwell committed
133

134
135
def test_exampleForest_P_shape():
    assert (Pf == array([[[0.1, 0.9, 0.0],
Steven Cordwell's avatar
Steven Cordwell committed
136
137
138
139
140
                         [0.1, 0.0, 0.9],
                         [0.1, 0.0, 0.9]],
                        [[1, 0, 0],
                         [1, 0, 0],
                         [1, 0, 0]]])).all()
141
142
143

def test_exampleForest_R_shape():
    assert (Rf == array([[0, 0],
Steven Cordwell's avatar
Steven Cordwell committed
144
145
146
                        [0, 1],
                        [4, 2]])).all()

Steven Cordwell's avatar
Steven Cordwell committed
147
148
149
def test_exampleForest_check():
    P, R = exampleForest(10, 5, 3, 0.2)
    assert check(P, R) == None
Steven Cordwell's avatar
Steven Cordwell committed
150
151

# exampleRand
Steven Cordwell's avatar
Steven Cordwell committed
152

153
154
155
P, R = exampleRand(STATES, ACTIONS)

def test_exampleRand_dense_P_shape():
Steven Cordwell's avatar
Steven Cordwell committed
156
    assert (P.shape == (ACTIONS, STATES, STATES))
157
158

def test_exampleRand_dense_R_shape():
Steven Cordwell's avatar
Steven Cordwell committed
159
160
    assert (R.shape == (ACTIONS, STATES, STATES))

Steven Cordwell's avatar
Steven Cordwell committed
161
162
def test_exampleRand_dense_check():
    assert check(P, R) == None
Steven Cordwell's avatar
Steven Cordwell committed
163

164
165
166
P, R = exampleRand(STATES, ACTIONS, is_sparse=True)

def test_exampleRand_sparse_P_shape():
Steven Cordwell's avatar
Steven Cordwell committed
167
    assert (P.shape == (ACTIONS, ))
168
169

def test_exampleRand_sparse_R_shape():
Steven Cordwell's avatar
Steven Cordwell committed
170
171
    assert (R.shape == (ACTIONS, ))

Steven Cordwell's avatar
Steven Cordwell committed
172
173
174
175
176
177
178
179
180
def test_exampleRand_sparse_check():
    assert check(P, R) == None

P = array([[[0.5, 0.5],[0.8, 0.2]],[[0, 1],[0.1, 0.9]]])
R = array([[5, 10], [-1, 2]])

# MDP

def test_MDP_P_R_1():
181
182
183
184
    P1 = zeros((2, ), dtype=object)
    P1[0] = matrix('0.5 0.5; 0.8 0.2')
    P1[1] = matrix('0 1; 0.1 0.9')
    R1 = matrix('5 10; -1 2')
185
    a = MDP(P, R, 0.9, 0.01)
Steven Cordwell's avatar
Steven Cordwell committed
186
187
188
189
190
191
192
193
    assert a.P.dtype == P1.dtype
    assert a.R.dtype == R1.dtype
    for kk in range(2):
        assert (a.P[kk] == P1[kk]).all()
    assert (a.R == R1).all()

def test_MDP_P_R_2():
    R = array([[[5, 10], [-1, 2]], [[1, 2], [3, 4]]])
194
195
196
197
    P1 = zeros((2, ), dtype=object)
    P1[0] = matrix('0.5 0.5; 0.8 0.2')
    P1[1] = matrix('0 1; 0.1 0.9')
    R1 = matrix('7.5 2; -0.4 3.9')
198
    a = MDP(P, R, 0.9, 0.01)
199
200
    assert type(a.P) == type(P1)
    assert type(a.R) == type(R1)
Steven Cordwell's avatar
Steven Cordwell committed
201
202
203
204
    assert a.P.dtype == P1.dtype
    assert a.R.dtype == R1.dtype
    for kk in range(2):
        assert (a.P[kk] == P1[kk]).all()
205
    assert (absolute(a.R - R1) < SMALLNUM).all()
Steven Cordwell's avatar
Steven Cordwell committed
206
207
208
209

def test_MDP_P_R_3():
    P = array([[[0.6116, 0.3884],[0, 1]],[[0.6674, 0.3326],[0, 1]]])
    R = array([[[-0.2433, 0.7073],[0, 0.1871]],[[-0.0069, 0.6433],[0, 0.2898]]])
210
    PR = matrix('0.12591304 0.20935652; 0.1871 0.2898')
Steven Cordwell's avatar
Steven Cordwell committed
211
    a = MDP(P, R, 0.9, 0.01)
212
    assert (absolute(a.R - PR) < SMALLNUM).all()
Steven Cordwell's avatar
Steven Cordwell committed
213

Steven Cordwell's avatar
Steven Cordwell committed
214
215
# ValueIteration

Steven Cordwell's avatar
Steven Cordwell committed
216
217
218
219
220
221
def test_ValueIteration_boundIter():
    inst = ValueIteration(P, R, 0.9, 0.01)
    assert (inst.max_iter == 28)

def test_ValueIteration_iterate():
    inst = ValueIteration(P, R, 0.9, 0.01)
Steven Cordwell's avatar
Steven Cordwell committed
222
223
224
225
226
    inst.iterate()
    assert (inst.value == (40.048625392716822,  33.65371175967546))
    assert (inst.policy == (1, 0))
    assert (inst.iter == 26)

Steven Cordwell's avatar
Steven Cordwell committed
227
228
229
230
231
232
def test_ValueIteration_exampleForest():
    P, R = exampleForest()
    a = ValueIteration(P, R, 0.96)
    a.iterate()
    assert (a.policy == array([0, 0, 0])).all()
    assert a.iter == 4
233

Steven Cordwell's avatar
Steven Cordwell committed
234
# PolicyIteration
Steven Cordwell's avatar
Steven Cordwell committed
235

236
237
def test_PolicyIteration_init_policy0():
    a = PolicyIteration(P, R, 0.9)
238
239
240
241
    p = matrix('1; 1')
    assert (a.policy == p).all()

def test_PolicyIteration_init_policy0_exampleForest():
242
    a = PolicyIteration(Pf, Rf, 0.9)
243
244
245
246
    p = matrix('0; 1; 0')
    assert (a.policy == p).all()

def test_PolicyIteration_computePpolicyPRpolicy_exampleForest():
247
    a = PolicyIteration(Pf, Rf, 0.9)
248
249
250
251
252
253
254
255
256
257
    P1 = matrix('0.1 0.9 0; 1 0 0; 0.1 0 0.9')
    R1 = matrix('0; 1; 4')
    Ppolicy, Rpolicy = a.computePpolicyPRpolicy()
    assert (absolute(Ppolicy - P1) < SMALLNUM).all()
    assert (absolute(Rpolicy - R1) < SMALLNUM).all()

def test_PolicyIteration_evalPolicyIterative_exampleForest():
    v0 = matrix('0; 0; 0')
    v1 = matrix('4.47504640074458; 5.02753258879703; 23.17234211944304')
    p = matrix('0; 1; 0')
258
    a = PolicyIteration(Pf, Rf, 0.9)
259
260
261
262
263
264
265
266
    assert (absolute(a.value - v0) < SMALLNUM).all()
    a.evalPolicyIterative()
    assert (absolute(a.value - v1) < SMALLNUM).all()
    assert (a.policy == p).all()

def test_PolicyIteration_evalPolicyIterative_bellmanOperator_exampleForest():
    v = matrix('4.47504640074458; 5.02753258879703; 23.17234211944304')
    p = matrix('0; 0; 0')
267
    a = PolicyIteration(Pf, Rf, 0.9)
268
269
270
271
272
273
    a.evalPolicyIterative()
    policy, value = a.bellmanOperator()
    assert (policy == p).all()
    assert (absolute(a.value - v) < SMALLNUM).all()

def test_PolicyIteration_iterative_exampleForest():
274
    a = PolicyIteration(Pf, Rf, 0.9, eval_type=1)
275
276
277
278
279
280
281
282
283
284
    V = matrix('26.2439058351861 29.4839058351861 33.4839058351861')
    p = matrix('0 0 0')
    itr = 2
    a.iterate()
    assert (absolute(array(a.value) - V) < SMALLNUM).all()
    assert (array(a.policy) == p).all()
    assert a.iter == itr

def test_PolicyIteration_evalPolicyMatrix_exampleForest():
    v_pol = matrix('4.47513812154696; 5.02762430939227; 23.17243384704857')
285
    a = PolicyIteration(Pf, Rf, 0.9)
286
287
288
289
    a.evalPolicyMatrix()
    assert (absolute(a.value - v_pol) < SMALLNUM).all()

def test_PolicyIteration_matrix_exampleForest():
290
    a = PolicyIteration(Pf, Rf, 0.9)
291
292
293
294
295
296
297
    V = matrix('26.2440000000000 29.4840000000000 33.4840000000000')
    p = matrix('0 0 0')
    itr = 2
    a.iterate()
    assert (absolute(array(a.value) - V) < SMALLNUM).all()
    assert (array(a.policy) == p).all()
    assert a.iter == itr
Steven Cordwell's avatar
Steven Cordwell committed
298

299
300
def test_ValueIterationGS():

Steven Cordwell's avatar
Steven Cordwell committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#def test_JacksCarRental():
#    S = 21 ** 2
#    A = 11
#    P = zeros((A, S, S))
#    R = zeros((A, S, S))
#    for a in range(A):
#        for s in range(21):
#            for s1 in range(21):
#                c1s = int(s / 21)
#                c2s = s - c1s * 21
#                c1s1 = int(s1 / 21)
#                c2s1 = s - c1s * 21
#                cs = c1s + c2s
#                cs1 = c1s1 + c2s1
#                netmove = 5 - a
#                if (s1 < s):
#                    pass
#                else:
#                    pass
#                P[a, s, s1] = 1
#                R[a, s, s1] = 10 * (cs - cs1) - 2 * abs(a)
#    
#    inst = PolicyIteration(P, R, 0.9)
#    inst.iterate()
#    #assert (inst.policy == )
#
#def test_JacksCarRental2():
#    pass
#
#def test_GamblersProblem():
#    inst = ValueIteration()
#    inst.iterate()
#    #assert (inst.policy == )
Steven Cordwell's avatar
Steven Cordwell committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352

# checkSquareStochastic: not square, stochastic and non-negative

#@raises(ValueError(mdperr["mat_square"]))
#def test_checkSquareStochastic_notsquare_stochastic_nonnegative_array():
#    P = eye(STATES, STATES + 1)
#    inst.checkSquareStochastic(P)
#
#@raises(ValueError(mdperr["mat_square"]))
#def test_checkSquareStochastic_notsquare_stochastic_nonnegative_matrix():
#    P = matrix(eye(STATES, STATES + 1))
#    inst.checkSquareStochastic(P)
#
#@raises(ValueError(mdperr["mat_square"]))
#def test_checkSquareStochastic_notsquare_stochastic_nonnegative_sparse():
#    P = speye(STATES, STATES + 1).tocsr()
#    inst.checkSquareStochastic(P)

# checkSquareStochastic: square, not stochastic and non-negative
Steven Cordwell's avatar
Steven Cordwell committed
353
    
Steven Cordwell's avatar
Steven Cordwell committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#def test_checkSquareStochastic_square_notstochastic_nonnegative_array():
#    P = eye(STATES)
#    i = randint(STATES)
#    j = randint(STATES)
#    P[i, j] = P[i, j] + 1
#    try:
#        inst.checkSquareStochastic(P)
#    except ValueError(mdperr["mat_stoch"]):
#        pass
#
#def test_checkSquareStochastic_square_notstochastic_nonnegative_matrix():
#    P = matrix(eye(STATES))
#    i = randint(STATES)
#    j = randint(STATES)
#    P[i, j] = P[i, j] + 1
#    try:
#        inst.checkSquareStochastic(P)
#    except ValueError(mdperr["mat_stoch"]):
#        pass
#
#def test_checkSquareStochastic_square_notstochastic_nonnegative_sparse():
#    P = speye(STATES, STATES).tolil()
#    i = randint(STATES)
#    j = randint(STATES)
#    P[i, j] = P[i, j] + 1
#    P = P.tocsr()
#    try:
#        inst.checkSquareStochastic(P)
#    except ValueError(mdperr["mat_stoch"]):
#        pass

# checkSquareStochastic: square, stochastic and negative

#def test_checkSquareStochastic_square_stochastic_negative_array():
#    P = eye(STATES, STATES)
#    i = randint(STATES)
#    j = randint(STATES)
#    while j == i:
#        j = randint(STATES)
#    P[i, i] = -1
#    P[i, j] = 1
#    try:
#        inst.checkSquareStochastic(P)
#    except ValueError(mdperr["mat_nonneg"]):
#        pass
#
#def test_checkSquareStochastic_square_stochastic_negative_matrix():
#    P = matrix(eye(STATES, STATES))
#    i = randint(STATES)
#    j = randint(STATES)
#    while j == i:
#        j = randint(STATES)
#    P[i, i] = -1
#    P[i, j] = 1
#    try:
#        inst.checkSquareStochastic(P)
#    except ValueError(mdperr["mat_nonneg"]):
#        pass
#
#def test_checkSquareStochastic_square_stochastic_negative_sparse():
#    P = speye(STATES, STATES)
#    i = randint(STATES)
#    j = randint(STATES)
#    while j == i:
#        j = randint(STATES)
#    P[i, i] = -1
#    P[i, j] = 1
#    try:
#        inst.checkSquareStochastic(P)
#    except ValueError(mdperr["mat_nonneg"]):
#        pass

#def test_check_square_stochastic_array_Rtranspose():
#    P = array([eye(STATES), eye(STATES)])
#    R = array([ones(STATES), ones(STATES)])
#    assert inst.check(P, R) == (True, "R is wrong way")