Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sourcery Starbot ⭐ refactored romanz/amodem #63

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions amodem/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ def __init__(self, stream):

def read(self, size):
while True:
data = self.stream.read(size)
if data:
if data := self.stream.read(size):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Compressor.read refactored with the following changes:

result = self.obj.compress(data)
if not result: # compression is too good :)
continue # try again (since falsy data = EOF)
Expand Down Expand Up @@ -88,12 +87,12 @@ def opener(fname):


def get_volume_cmd(args):
volume_controllers = [
dict(test='pactl --version',
send='pactl set-sink-volume @DEFAULT_SINK@',
recv='pactl set-source-volume @DEFAULT_SOURCE@')
]
if args.calibrate == 'auto':
volume_controllers = [
dict(test='pactl --version',
send='pactl set-sink-volume @DEFAULT_SINK@',
recv='pactl set-source-volume @DEFAULT_SOURCE@')
]
Comment on lines -91 to +95
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_volume_cmd refactored with the following changes:

for c in volume_controllers:
if os.system(c['test']) == 0:
return c[args.command]
Expand Down
17 changes: 8 additions & 9 deletions amodem/calib.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,7 @@ def detector(config, src, frame_length=200):
flags = [total > 0.1, peak < 1.0, coherency > 0.99]

success = all(flags)
if success:
msg = 'good signal'
else:
msg = f'too {errors[flags.index(False)]} signal'

msg = 'good signal' if success else f'too {errors[flags.index(False)]} signal'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function detector refactored with the following changes:

yield dict(
freq=freq, rms=rms, peak=peak, coherency=coherency,
total=total, success=success, msg=msg
Expand Down Expand Up @@ -123,10 +119,13 @@ def recv_iter(config, src, volume_cmd=None, dump_audio=None):
result_iterator = volume_calibration(result_iterator, volume_ctl)
for _prev, curr, _next in iter_window(result_iterator, size=3):
# don't log errors during frequency changes
if _prev['success'] and _next['success']:
if _prev['freq'] != _next['freq']:
if not curr['success']:
curr['msg'] = 'frequency change'
if (
_prev['success']
and _next['success']
and _prev['freq'] != _next['freq']
and not curr['success']
):
curr['msg'] = 'frequency change'
Comment on lines -126 to +128
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function recv_iter refactored with the following changes:

yield curr


Expand Down
3 changes: 1 addition & 2 deletions amodem/detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,7 @@ def find_start(self, buf):

index = np.argmax(coeffs)
log.info('Carrier coherence: %.3f%%', coeffs[index] * 100)
offset = index + len(zeroes)
return offset
return index + len(zeroes)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Detector.find_start refactored with the following changes:


def estimate(self, buf, skip=5):
filt = dsp.exp_iwt(-self.omega, self.Nsym) / (0.5 * self.Nsym)
Expand Down
4 changes: 1 addition & 3 deletions amodem/dsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ def coherence(x, omega):
n = len(x)
Hc = exp_iwt(-omega, n) / np.sqrt(0.5*n)
norm_x = norm(x)
if not norm_x:
return 0.0
return np.dot(Hc, x) / norm_x
return np.dot(Hc, x) / norm_x if norm_x else 0.0
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function coherence refactored with the following changes:



def linear_regression(x, y):
Expand Down
12 changes: 5 additions & 7 deletions amodem/equalizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,18 @@ def train_symbols(self, length, constant_prefix=16):
r = dsp.prbs(reg=1, poly=0x1100b, bits=2)
constellation = [1, 1j, -1, -1j]

symbols = []
for _ in range(length):
symbols.append([constellation[next(r)] for _ in range(self.Nfreq)])

symbols = [
[constellation[next(r)] for _ in range(self.Nfreq)]
for _ in range(length)
]
Comment on lines -24 to +27
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Equalizer.train_symbols refactored with the following changes:

symbols = np.array(symbols)
# Constant symbols (for analog debugging)
symbols[:constant_prefix, :] = 1
return symbols

def modulator(self, symbols):
gain = 1.0 / len(self.carriers)
result = []
for s in symbols:
result.append(np.dot(s, self.carriers))
result = [np.dot(s, self.carriers) for s in symbols]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Equalizer.modulator refactored with the following changes:

result = np.concatenate(result).real * gain
assert np.max(np.abs(result)) <= 1
return result
Expand Down
4 changes: 2 additions & 2 deletions amodem/framing.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ def __init__(self):
bits = [index & (2 ** k) for k in range(self.byte_size)]
bits_list.append(tuple((1 if b else 0) for b in bits))

self.to_bits = dict((i, bits) for i, bits in enumerate(bits_list))
self.to_byte = dict((bits, i) for i, bits in enumerate(bits_list))
self.to_bits = dict(enumerate(bits_list))
self.to_byte = {bits: i for i, bits in enumerate(bits_list)}
Comment on lines -98 to +99
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BitPacker.__init__ refactored with the following changes:



@chain_wrapper
Expand Down
2 changes: 1 addition & 1 deletion amodem/recv.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def _handler(received, decoded, freq):
log.info('Starting demodulation')
for i, block_of_bits in enumerate(stream, 1):
for bits in block_of_bits:
self.stats['rx_bits'] = self.stats['rx_bits'] + len(bits)
self.stats['rx_bits'] += len(bits)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Receiver._demodulate refactored with the following changes:

  • Replace assignment with augmented assignment (aug-assign)

yield bits

if i % self.iters_per_update == 0:
Expand Down
2 changes: 1 addition & 1 deletion amodem/sampling.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def __init__(self, resolution=1024, width=128):
lengths = [len(f) for f in self.filt]
self.coeff_len = 2 * width

assert set(lengths) == set([self.coeff_len]) # verify same lengths
assert set(lengths) == {self.coeff_len}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Interpolator.__init__ refactored with the following changes:

This removes the following comments ( why? ):

# verify same lengths

assert len(self.filt) == resolution


Expand Down
6 changes: 2 additions & 4 deletions amodem/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ def __iter__(self):
def next(self):
block = bytearray()
if self.eof:
data = self.fd.read(self.bufsize)
if data:
if data := self.fd.read(self.bufsize):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Reader.next refactored with the following changes:

self.total += len(data)
block.extend(data)
return block
Expand All @@ -29,8 +28,7 @@ def next(self):
finish_time = time.time() + self.timeout
while time.time() <= finish_time:
left = self.bufsize - len(block)
data = self.fd.read(left)
if data:
if data := self.fd.read(left):
self.total += len(data)
block.extend(data)

Expand Down
2 changes: 1 addition & 1 deletion amodem/tests/test_calib.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def test_too_weak():

def test_too_noisy():
r = random.Random(0) # generate random binary signal
signal = np.array([r.choice([-1, 1]) for i in range(int(config.Fs))])
signal = np.array([r.choice([-1, 1]) for _ in range(int(config.Fs))])
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_too_noisy refactored with the following changes:

src = BytesIO(common.dumps(signal * 0.5))
for r in calib.detector(config, src=src):
assert not r['success']
Expand Down
11 changes: 4 additions & 7 deletions amodem/tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@

def iterlist(x, *args, **kwargs):
x = np.array(x)
return list(
(i, list(x))
for i, x in common.iterate(x, index=True, *args, **kwargs)
)
return [
(i, list(x)) for i, x in common.iterate(x, index=True, *args, **kwargs)
]
Comment on lines -8 to +10
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function iterlist refactored with the following changes:



def test_iterate():
Expand All @@ -35,9 +34,7 @@ def test_split():
def test_icapture():
x = range(100)
y = []
z = []
for i in common.icapture(x, result=y):
z.append(i)
z = list(common.icapture(x, result=y))
Comment on lines -38 to +37
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_icapture refactored with the following changes:

assert list(x) == y
assert list(x) == z

Expand Down
5 changes: 2 additions & 3 deletions amodem/tests/test_dsp.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def quantize(q, s):
def test_overflow():
q = dsp.MODEM(config.symbols)
r = np.random.RandomState(seed=0)
for i in range(10000):
for _ in range(10000):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_overflow refactored with the following changes:

s = 10*(r.normal() + 1j * r.normal())
quantize(q, s)

Expand All @@ -88,6 +88,5 @@ def test_prbs():
assert r == [1, 2, 0, 1, 3, 3, 2, 1]

period = 2 ** 16 - 1
r = list(itertools.islice(dsp.prbs(reg=1, poly=0x1100b, bits=16), period))
r.sort()
r = sorted(itertools.islice(dsp.prbs(reg=1, poly=0x1100b, bits=16), period))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_prbs refactored with the following changes:

assert r == list(range(1, 2 ** 16))
2 changes: 1 addition & 1 deletion amodem/tests/test_framing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def concat(iterable):


r = random.Random(0)
blob = bytearray(r.randrange(0, 256) for i in range(64 * 1024))
blob = bytearray(r.randrange(0, 256) for _ in range(64 * 1024))
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 13-13 refactored with the following changes:



@pytest.fixture(params=[b'', b'abc', b'1234567890', blob, blob[:12345]])
Expand Down
5 changes: 1 addition & 4 deletions amodem/tests/test_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,9 @@ def test_read():
result = list(zip(range(10), f))
p.kill()

j = 0
for i, buf in result:
for j, (i, buf) in enumerate(result):
assert i == j
assert len(buf) == f.bufsize
j += 1

Comment on lines -26 to -31
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_read refactored with the following changes:

try:
next(f)
except IOError as e:
Expand Down