File size: 9,492 Bytes
079c32c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
from collections import namedtuple

import numpy as np
import pytest
import torch
import treetensor.torch as ttorch

from ding.utils.default_helper import lists_to_dicts, dicts_to_lists, squeeze, default_get, override, error_wrapper, \
    list_split, LimitedSpaceContainer, set_pkg_seed, deep_merge_dicts, deep_update, flatten_dict, RunningMeanStd, \
    one_time_warning, split_data_generator, get_shape0


@pytest.mark.unittest
class TestDefaultHelper():

    def test_get_shape0(self):
        a = {
            'a': {
                'b': torch.randn(4, 3)
            },
            'c': {
                'd': torch.randn(4)
            },
        }
        b = [a, a]
        c = (a, a)
        d = {
            'a': {
                'b': ["a", "b", "c", "d"]
            },
            'c': {
                'd': torch.randn(4)
            },
        }
        a = ttorch.as_tensor(a)
        assert get_shape0(a) == 4
        assert get_shape0(b) == 4
        assert get_shape0(c) == 4
        with pytest.raises(Exception) as e_info:
            assert get_shape0(d) == 4

    def test_lists_to_dicts(self):
        set_pkg_seed(12)
        with pytest.raises(ValueError):
            lists_to_dicts([])
        with pytest.raises(TypeError):
            lists_to_dicts([1])
        assert lists_to_dicts([{1: 1, 10: 3}, {1: 2, 10: 4}]) == {1: [1, 2], 10: [3, 4]}
        T = namedtuple('T', ['location', 'race'])
        data = [T({'x': 1, 'y': 2}, 'zerg') for _ in range(3)]
        output = lists_to_dicts(data)
        assert isinstance(output, T) and output.__class__ == T
        assert len(output.location) == 3
        data = [{'value': torch.randn(1), 'obs': {'scalar': torch.randn(4)}} for _ in range(3)]
        output = lists_to_dicts(data, recursive=True)
        assert isinstance(output, dict)
        assert len(output['value']) == 3
        assert len(output['obs']['scalar']) == 3

    def test_dicts_to_lists(self):
        assert dicts_to_lists({1: [1, 2], 10: [3, 4]}) == [{1: 1, 10: 3}, {1: 2, 10: 4}]

    def test_squeeze(self):
        assert squeeze((4, )) == 4
        assert squeeze({'a': 4}) == 4
        assert squeeze([1, 3]) == (1, 3)
        data = np.random.randn(3)
        output = squeeze(data)
        assert (output == data).all()

    def test_default_get(self):
        assert default_get({}, 'a', default_value=1, judge_fn=lambda x: x < 2) == 1
        assert default_get({}, 'a', default_fn=lambda: 1, judge_fn=lambda x: x < 2) == 1
        with pytest.raises(AssertionError):
            default_get({}, 'a', default_fn=lambda: 1, judge_fn=lambda x: x < 0)
        assert default_get({'val': 1}, 'val', default_value=2) == 1

    def test_override(self):

        class foo(object):

            def fun(self):
                raise NotImplementedError

        class foo1(foo):

            @override(foo)
            def fun(self):
                return "a"

        with pytest.raises(NameError):

            class foo2(foo):

                @override(foo)
                def func(self):
                    pass

        with pytest.raises(NotImplementedError):
            foo().fun()
        foo1().fun()

    def test_error_wrapper(self):

        def good_ret(a, b=1):
            return a + b

        wrap_good_ret = error_wrapper(good_ret, 0)
        assert good_ret(1) == wrap_good_ret(1)

        def bad_ret(a, b=0):
            return a / b

        wrap_bad_ret = error_wrapper(bad_ret, 0)
        assert wrap_bad_ret(1) == 0
        wrap_bad_ret_with_customized_log = error_wrapper(bad_ret, 0, 'customized_information')

    def test_list_split(self):
        data = [i for i in range(10)]
        output, residual = list_split(data, step=4)
        assert len(output) == 2
        assert output[1] == [4, 5, 6, 7]
        assert residual == [8, 9]
        output, residual = list_split(data, step=5)
        assert len(output) == 2
        assert output[1] == [5, 6, 7, 8, 9]
        assert residual is None


@pytest.mark.unittest
class TestLimitedSpaceContainer():

    def test_container(self):
        container = LimitedSpaceContainer(0, 5)
        first = container.acquire_space()
        assert first
        assert container.cur == 1
        left = container.get_residual_space()
        assert left == 4
        assert container.cur == container.max_val == 5
        no_space = container.acquire_space()
        assert not no_space
        container.increase_space()
        six = container.acquire_space()
        assert six
        for i in range(6):
            container.release_space()
            assert container.cur == 5 - i
        container.decrease_space()
        assert container.max_val == 5


@pytest.mark.unittest
class TestDict:

    def test_deep_merge_dicts(self):
        dict1 = {
            'a': 3,
            'b': {
                'c': 3,
                'd': {
                    'e': 6,
                    'f': 5,
                }
            }
        }
        dict2 = {
            'b': {
                'c': 5,
                'd': 6,
                'g': 4,
            }
        }
        new_dict = deep_merge_dicts(dict1, dict2)
        assert new_dict['a'] == 3
        assert isinstance(new_dict['b'], dict)
        assert new_dict['b']['c'] == 5
        assert new_dict['b']['c'] == 5
        assert new_dict['b']['g'] == 4

    def test_deep_update(self):
        dict1 = {
            'a': 3,
            'b': {
                'c': 3,
                'd': {
                    'e': 6,
                    'f': 5,
                },
                'z': 4,
            }
        }
        dict2 = {
            'b': {
                'c': 5,
                'd': 6,
                'g': 4,
            }
        }
        with pytest.raises(RuntimeError):
            new1 = deep_update(dict1, dict2, new_keys_allowed=False)
        new2 = deep_update(dict1, dict2, new_keys_allowed=False, whitelist=['b'])
        assert new2['a'] == 3
        assert new2['b']['c'] == 5
        assert new2['b']['d'] == 6
        assert new2['b']['g'] == 4
        assert new2['b']['z'] == 4

        dict1 = {
            'a': 3,
            'b': {
                'type': 'old',
                'z': 4,
            }
        }
        dict2 = {
            'b': {
                'type': 'new',
                'c': 5,
            }
        }
        new3 = deep_update(dict1, dict2, new_keys_allowed=True, whitelist=[], override_all_if_type_changes=['b'])
        assert new3['a'] == 3
        assert new3['b']['type'] == 'new'
        assert new3['b']['c'] == 5
        assert 'z' not in new3['b']

    def test_flatten_dict(self):
        dict = {
            'a': 3,
            'b': {
                'c': 3,
                'd': {
                    'e': 6,
                    'f': 5,
                },
                'z': 4,
            }
        }
        flat = flatten_dict(dict)
        assert flat['a'] == 3
        assert flat['b/c'] == 3
        assert flat['b/d/e'] == 6
        assert flat['b/d/f'] == 5
        assert flat['b/z'] == 4

    def test_one_time_warning(self):
        one_time_warning('test_one_time_warning')

    def test_running_mean_std(self):
        running = RunningMeanStd()
        running.reset()
        running.update(np.arange(1, 10))
        assert running.mean == pytest.approx(5, abs=1e-4)
        assert running.std == pytest.approx(2.582030, abs=1e-6)
        running.update(np.arange(2, 11))
        assert running.mean == pytest.approx(5.5, abs=1e-4)
        assert running.std == pytest.approx(2.629981, abs=1e-6)
        running.reset()
        running.update(np.arange(1, 10))
        assert pytest.approx(running.mean, abs=1e-4) == 5
        assert running.mean == pytest.approx(5, abs=1e-4)
        assert running.std == pytest.approx(2.582030, abs=1e-6)
        new_shape = running.new_shape((2, 4), (3, ), (1, ))
        assert isinstance(new_shape, tuple) and len(new_shape) == 3

        running = RunningMeanStd(shape=(4, ))
        running.reset()
        running.update(np.random.random((10, 4)))
        assert isinstance(running.mean, torch.Tensor) and running.mean.shape == (4, )
        assert isinstance(running.std, torch.Tensor) and running.std.shape == (4, )

    def test_split_data_generator(self):

        def get_data():
            return {
                'obs': torch.randn(5),
                'action': torch.randint(0, 10, size=(1, )),
                'prev_state': [None, None],
                'info': {
                    'other_obs': torch.randn(5)
                },
            }

        data = [get_data() for _ in range(4)]
        data = lists_to_dicts(data)
        data['obs'] = torch.stack(data['obs'])
        data['action'] = torch.stack(data['action'])
        data['info'] = {'other_obs': torch.stack([t['other_obs'] for t in data['info']])}
        assert len(data['obs']) == 4
        data['NoneKey'] = None
        generator = split_data_generator(data, 3)
        generator_result = list(generator)
        assert len(generator_result) == 2
        assert generator_result[0]['NoneKey'] is None
        assert len(generator_result[0]['obs']) == 3
        assert generator_result[0]['info']['other_obs'].shape == (3, 5)
        assert generator_result[1]['NoneKey'] is None
        assert len(generator_result[1]['obs']) == 3
        assert generator_result[1]['info']['other_obs'].shape == (3, 5)

        generator = split_data_generator(data, 3, shuffle=False)