Refactor iteration.

This commit is contained in:
Roman Zeyde
2014-07-04 08:37:55 +03:00
committed by Roman Zeyde
parent 4f5678f687
commit 40915f4f15
3 changed files with 40 additions and 10 deletions

View File

@@ -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

10
recv.py
View File

@@ -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

18
test_common.py Normal file
View File

@@ -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)]