Skip to content

Instantly share code, notes, and snippets.

@estysdesu
Last active March 25, 2020 20:30
Show Gist options
  • Save estysdesu/82f91496557f8de005698b9d28d6563d to your computer and use it in GitHub Desktop.
Save estysdesu/82f91496557f8de005698b9d28d6563d to your computer and use it in GitHub Desktop.
[Python: Downsample] #downsample #matlab #itertools
import itertools
def downsample(x, n, phase=0, roll=False):
"""
Downsampling compatible with Matlab's implementation, plus an
additonal argument of roll to allow rolling the end of the iterable
into the beginning when phase is greater than 0.
Args:
x: iterable to be downsampled
n: downsampling factor
phase: offset start(default: 0)
roll: whether to roll x
Return:
list containing the downsampled iterable
"""
if not isinstance(phase, int):
raise ValueError("phase must be an integer")
if not isinstance(n, int):
raise ValueError("n must be an integer")
if roll:
if phase == 0:
raise ValueError("phase must be set to enable roll")
elif phase < 0:
raise ValueError("phase must be a positve offset value")
x = itertools.chain(x, x[:phase])
y = itertools.islice(x, phase, None, n)
return list(y)
from typing import *
def downsample(
x: Iterable[Any], n: int, phase: int = ..., roll: bool = ...
) -> Iterable[Any]: ...
import unittest
import math
import itertools
form downsample import downsample
class TestDownsample(unittest.TestCase):
def test_downsample(self):
n = 3
p = 1
r = True
a = [(x*10)-3 for x in range(17)]
b1 = downsample(a, n, phase=p, roll=r)
if r:
i = [0, 1, 0]*(math.ceil(len(a)/n))
else:
i = [0, 1, 0]*(len(a)//n)
b2 = list(itertools.compress(a, i))
self.assertEqual(b1, b2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment