Skip to content

Instantly share code, notes, and snippets.

@mitkof6
Last active July 31, 2017 13:42
Show Gist options
  • Save mitkof6/9d8388c09f291c6b9b3e68ee1c7ea5bc to your computer and use it in GitHub Desktop.
Save mitkof6/9d8388c09f291c6b9b3e68ee1c7ea5bc to your computer and use it in GitHub Desktop.
a simple signal delay component for python
#!/usr/bin/env python
import numpy as np
import pylab as pl
import unittest
from scipy.interpolate import CubicSpline
class Delay:
"""Implements a signal delay.
We assume that values prior to the delay are zero (y(t < t_c - d) =
0). Moreover we define a memory variable that is 10 x delay and restricts
the size of the buffer.
"""
def __init__(self, delay):
"""
"""
self.t = []
self.y = []
self.delay = delay
self.memory = 10.0 * delay
def add(self, t, y):
"""Append the delay buffer with the current value of the signal.
Restrict the buffer to contain values coresponding to:
[current time - memory (10.0 x delay)]
"""
# append container
self.t.append(t)
self.y.append(y)
# remove before delay
t = np.array(self.t)
y = np.array(self.y)
select = t >= t[-1] - self.memory
# sort (must be inceasing in t)
sort = np.argsort(t)
t = t[sort]
y = y[sort]
# update container
self.t = t[select].tolist()
self.y = y[select].tolist()
def get_delayed(self):
"""Get a delaied version of the signal (CubicSpline).
"""
t = self.t
y = self.y
d = self.delay
# 2
if len(t) == 2 and t[-1] - d >= 0:
return y[0] + (y[1] - y[0]) / (t[1] - t[0]) * (d - t[0])
# < 3
if len(t) < 3 or t[-1] - d < 0:
return 0
# 3+
cs = CubicSpline(np.array(t), np.array(y))
return cs(t[-1] - d)
class TestDelay(unittest.TestCase):
def test_delay(self):
d = np.pi / 2
delay = Delay(d)
t = np.linspace(0, 2.5 * np.pi, num=100, endpoint=True)
y = []
yd = []
for i in t:
y.append(np.sin(i) + 0.1 * np.cos(7 * i))
delay.add(i, y[-1])
yd.append(delay.get_delayed())
# plot
pl.figure()
pl.plot(t, y, 'r', t, yd, 'b')
pl.title('Delay = ' + str(d))
pl.xlabel('$t \; (s)$')
pl.ylabel('$y(t)$')
pl.legend(['$y(t)$', '$y(t-d)$'])
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment