def test_StreamCollection(self): a = Stream([0, 1, 2, 3]) b = Stream([5, 6, 7, 8]) c = Stream([-1, -2, -3]) coll = StreamCollection([a, b, c]) self.assertEquals(a.peek(4), coll.take(4)) self.assertEquals(b.peek(4), coll.take(4)) self.assertEquals(c.peek(3), coll.take(3))
def ttl_single_uri_data(mdata, start_indent_level=1, indent_size=2, extra_space=True): """ String with the Turtle code for a single URI. Alike to ``ttl_tokens``, but already prepared for a whole URI data (i.e., ``main = True``) and yields extra spacing "pseudo-tokens". Join together to get an aligned Turtle code. Parameters ---------- mdata : A dictionary with the whole metadata for an URI. start_indent_level : Choose whether there's a starting indentation step for the generated code. indent_size : Length for the indentation step, i.e., the amount of spaces to be used. extra_space : Boolean to choose whether there should be an extra space between each "triple" (a ``mdata`` item, in this implementation "prefix:name" is just a single key) in the main "collection" (``mdata`` itself). """ indent_level = start_indent_level tokens = Stream(ttl_tokens(mdata, main=True)) if tokens.peek(1): # Has at least one token yield " " * indent_size * indent_level new_line = True for token in tokens: if token == "[": if not new_line: yield " " yield token indent_level += 1 if tokens.peek(1) != ["]"]: yield "\n" yield " " * indent_size * indent_level new_line = True elif token == ";": yield token yield "\n" if extra_space and indent_level == start_indent_level: yield "\n" yield " " * indent_size * (indent_level - (tokens.peek(1) == ["]"])) new_line = True elif token in [",", "."]: yield token new_line = False else: if not new_line: yield " " yield token if token == "]": indent_level -= 1 new_line = False
def get_fundfreq(fs, audio, order=12, mode='covariance'): import audiolazy as AL from audiolazy import Stream modes = {'covariance', 'autocorrelation'} if mode not in modes: raise Exception( "The value for mode needs to be either 'covariance' or 'autocorrelation'" ) if mode == 'covariance': filt_func = AL.lpc.covariance if mode == 'autocorrelation': filt_func = AL.lpc.autocorrelation inv_filt = filt_func(audio, order) sig = audio.copy() sig_ = inv_filt(Stream(sig)).take(len(sig)) sub = sig - sig_ autocorr = np.correlate(sub, sub, 'same') autocorr = autocorr[int(len(autocorr) / 2):] ind_locmax = np.squeeze(argrelextrema(autocorr, np.greater)) locmax = autocorr[ind_locmax] pitch_period = ind_locmax[np.argmax(locmax)] fundamental_freq = fs / pitch_period return fundamental_freq
def taylor(f, n=2, **kwargs): """ Taylor/Mclaurin polynomial aproximation for the given function. The ``n`` (default 2) is the amount of aproximation terms for ``f``. Other arguments are keyword-only and will be passed to the ``f.series`` method. """ return sum(Stream(f.series(n=None, **kwargs)).limit(n))
def get_peaks(blk, neighbors=2): """ Get all peak indices in blk (sorted by index value) but the ones at the vector limits (first and last ``neighbors - 1`` values). A peak is the max value in a neighborhood of ``neighbors`` values for each side. """ size = 1 + 2 * neighbors pairs = enumerate(Stream(blk).blocks(size=size, hop=1).map(list), neighbors) for idx, nbhood in pairs: center = nbhood.pop(neighbors) if all(center >= el for el in nbhood): yield idx next(pairs) # Skip ones we already know can't be peaks next(pairs)
def mgl_seq(x): """ Sequence whose sum is the Madhava-Gregory-Leibniz series. [x, -x^3/3, x^5/5, -x^7/7, x^9/9, -x^11/11, ...] Returns ------- An endless sequence that has the property ``atan(x) = sum(mgl_seq(x))``. Usually you would use the ``atan()`` function, not this one. """ odd_numbers = thub(count(start=1, step=2), 2) return Stream(1, -1) * x ** odd_numbers / odd_numbers
def test(filepath): fs, audio = wavread(filepath) # IPython.display.Audio(filepath) import audiolazy as AL from audiolazy import Stream filt = AL.lpc.covariance(audio, order=10) sig = audio.copy() s = Stream(audio.copy()) sig_ = filt(s).take(len(sig)) N = -600 plt.subplot(211) plt.plot(sig[N:], linewidth=0.5, label='Original signal $s[n]$') plt.plot(sig_[N:], linewidth=0.5, label=u'Filtered $\hat{s}[n]$', alpha=0.5) plt.title(filepath) plt.legend() plt.subplot(212) plt.plot(sig[N:] - sig_[N:], linewidth=0.5, label=u'$s[n] - \hat{s}[n]$') plt.legend()
def limiter(sig, threshold=.1, size=256, env=envelope.rms, cutoff=pi / 2048): sig = thub(sig, 2) return sig * Stream(1. if el <= threshold else threshold / el for el in maverage(size)(env(sig, cutoff=cutoff)))
# along with this program. If not, see <http://www.gnu.org/licenses/>. """ LPTV (Linear Periodically Time Variant) filter example (a.k.a. PLTV) """ from audiolazy import sHz, sinusoid, Stream, AudioIO, z, pi, chunks import time, sys # Basic initialization rate = 44100 s, Hz = sHz(rate) # Some time-variant coefficients cycle_a1 = [.1, .2, .1, 0, -.1, -.2, -.1, 0] cycle_a2 = [.1, 0, -.1, 0, 0] a1 = Stream(*cycle_a1) a2 = Stream(*cycle_a2) * 2 b1 = sinusoid(18 * Hz) # Sine phase b2 = sinusoid(freq=7 * Hz, phase=pi / 2) # Cosine phase # The filter filt = (1 + b1 * z**-1 + b2 * z**-2 + .7 * z**-5) filt /= (1 - a1 * z**-1 - a2 * z**-2 - .1 * z**-3) # A really simple input input_data = sinusoid(220 * Hz) # Let's play it! api = sys.argv[1] if sys.argv[1:] else None # Choose API via command-line chunks.size = 1 if api == "jack" else 16 with AudioIO(api=api) as player:
def dft_pitch(sig, size=2048, hop=None): for blk in Stream(sig).blocks(size=size, hop=hop): dft_data = rfft(blk) idx, vmax = max(enumerate(dft_data), key=lambda el: abs(el[1]) / (2 * el[0] / size + 1)) yield 2 * pi * idx / size
def overlap_correlation(wnd, hop): """ Overlap correlation percent for the given overlap hop in samples. """ return sum(wnd * Stream(wnd).skip(hop)) / sum(el**2 for el in wnd)
#!/usr/bin/env python # coding: utf-8 # MIT Licenced # @authors: Danilo J. S. Bellini # Eduardo F. Mendes # Renato G. Rodrigues # Victor Mendizabal # Otto Heringer # Danilo Vieira # # Regular time-alternated one-LED blinking with AudioLazy for Raspberry Pi import RPi.GPIO as gpio from time import sleep from audiolazy import Stream gpio.setmode(gpio.BOARD) gpio.setup(11, gpio.OUT) for idx, delay in enumerate(Stream(1, 2, 2, 1)): gpio.output(11, int(idx % 2 == 0)) sleep(delay * .2)