From 40915f4f1535e823c4e9f67fa06370feafec739e Mon Sep 17 00:00:00 2001 From: Roman Zeyde Date: Fri, 4 Jul 2014 08:37:55 +0300 Subject: [PATCH] Refactor iteration. --- common.py | 22 ++++++++++++++++++++++ recv.py | 10 ---------- test_common.py | 18 ++++++++++++++++++ 3 files changed, 40 insertions(+), 10 deletions(-) create mode 100644 test_common.py diff --git a/common.py b/common.py index de9cdc3..e9c1b49 100644 --- a/common.py +++ b/common.py @@ -52,6 +52,28 @@ def dumps(sym, n=1): def norm(x): return np.sqrt(np.dot(x.conj(), x).real) + +def iterate(data, bufsize, offset=0, advance=1, func=None): + assert bufsize > 0 + assert offset >= 0 + assert advance > 0 + buf = np.zeros(bufsize) + buf_index = 0 + for data_index, value in enumerate(data): + if data_index < offset: + continue + + buf[buf_index] = value + buf_index += 1 + + if buf_index == bufsize: + result = func(buf) if func else buf + print offset, result + yield offset, result + buf[:-advance] = buf[advance:] + buf_index = max(0, buf_index - advance) + offset += advance + if __name__ == '__main__': import pylab diff --git a/recv.py b/recv.py index c00dd2c..113c935 100644 --- a/recv.py +++ b/recv.py @@ -17,16 +17,6 @@ CARRIER_THRESHOLD = int(0.9 * CARRIER_DURATION) def power(x): return np.dot(x.conj(), x).real / len(x) -def iterate(x, bufsize, offset=0, advance=1, func=None): - while True: - buf = x[offset:offset+bufsize] - if len(buf) == bufsize: - result = func(buf) if func else buf - yield offset, result - else: - return - offset += advance - def exp_iwt(freq, n): iw = 2j * np.pi * freq t = np.arange(n) * Ts diff --git a/test_common.py b/test_common.py new file mode 100644 index 0000000..5825ced --- /dev/null +++ b/test_common.py @@ -0,0 +1,18 @@ +import common +import numpy as np + +def iterlist(x, *args, **kwargs): + x = np.array(x) + return [(offset, list(buf)) for offset, buf in common.iterate(x, *args, **kwargs)] + +def test_iterate(): + N = 10 + assert iterlist(range(N), 1) == [(i, [i]) for i in range(N)] + assert iterlist(range(N), 1) == [(i, [i]) for i in range(N)] + assert iterlist(range(N), 2) == [(i, [i, i+1]) for i in range(N-1)] + assert iterlist(range(N), 3) == [(i, [i, i+1, i+2]) for i in range(N-2)] + assert iterlist(range(N), 3, advance=2) == [(i, [i, i+1, i+2]) for i in range(0, N-2, 2)] + assert iterlist(range(N), 3, advance=3) == [(i, [i, i+1, i+2]) for i in range(0, N-2, 3)] + assert iterlist(range(N), 2, offset=5) == [(i, [i, i+1]) for i in range(5, N-1)] + assert iterlist(range(N), 1, func=lambda b: -b) == [(i, [-i]) for i in range(N)] +