|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | +from os import path |
| 6 | +sys.path.append(path.join(path.dirname(path.abspath(__file__)), os.pardir)) |
| 7 | + |
| 8 | +from helpers import RingBuffer, MeanVarHistory |
| 9 | +import numpy as np |
| 10 | + |
| 11 | + |
| 12 | +def test_ring_buffer(): |
| 13 | + buf = RingBuffer(5) |
| 14 | + |
| 15 | + buf.append(1) |
| 16 | + buf.append(2) |
| 17 | + print buf.get() |
| 18 | + assert np.array_equal(buf.get(), np.array([1,2])) |
| 19 | + assert buf.get().dtype == np.float |
| 20 | + buf.reset() |
| 21 | + |
| 22 | + for i in xrange(1, 7): |
| 23 | + buf.append(i) |
| 24 | + print buf.get() |
| 25 | + assert np.array_equal(buf.get(), np.array([2,3,4,5,6])) |
| 26 | + buf.reset() |
| 27 | + |
| 28 | + print buf.get() |
| 29 | + assert np.array_equal(buf.get(), np.array([])) |
| 30 | + |
| 31 | + print 'test_ring_buffer: success' |
| 32 | + |
| 33 | + |
| 34 | +def test_mean_var_history(): |
| 35 | + h = MeanVarHistory() |
| 36 | + |
| 37 | + h.append([1,2,3]) |
| 38 | + h.append(np.array([4,5])) |
| 39 | + print h.get_mean(), h.get_var(), h.get_std() |
| 40 | + |
| 41 | + correct = np.array([1,2,3,4,5]) |
| 42 | + assert np.isclose(h.get_mean(), np.mean(correct)) |
| 43 | + assert np.isclose(h.get_var(), np.var(correct)) |
| 44 | + assert np.isclose(h.get_std(), np.std(correct)) |
| 45 | + |
| 46 | + h.reset() |
| 47 | + |
| 48 | + h.append([1,1,1]) |
| 49 | + print h.normalize_copy([2,3,4]) |
| 50 | + assert np.allclose(h.normalize_copy([2,3,4]), np.array([1e5, 2e5, 3e5])) |
| 51 | + |
| 52 | + h.append([3,3,3]) |
| 53 | + x = np.array([2.0, 4.0]) |
| 54 | + h.normalize_inplace(x) |
| 55 | + print x |
| 56 | + assert np.allclose(x, np.array([0.0, 2.0])) |
| 57 | + |
| 58 | + print 'test_mean_var_history: success' |
| 59 | + |
| 60 | + |
| 61 | +def main(): |
| 62 | + test_ring_buffer() |
| 63 | + test_mean_var_history() |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + main() |
0 commit comments