Last active
March 25, 2020 20:30
-
-
Save estysdesu/82f91496557f8de005698b9d28d6563d to your computer and use it in GitHub Desktop.
[Python: Downsample] #downsample #matlab #itertools
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import * | |
def downsample( | |
x: Iterable[Any], n: int, phase: int = ..., roll: bool = ... | |
) -> Iterable[Any]: ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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