<jupyter_start><jupyter_text>Let's compute K-S algorithm$$    y[n] = x[n] + alpha * y[n - M]$$assuming that the input is the finite-support signal$$x[n] = \begin{cases}    0 & \mbox{for $n < 0$} \\    b_n & \mbox{for $0 \le n < len(x)$}  \end{cases}$$<jupyter_code>## Math
import numpy as np

## nd.array deep copy
import copy

## Audio Playing
from IPython.display import Audio

## Wave file save
import scipy.io.wavfile as wavfile

## Visualization
%matplotlib inline
import matplotlib.pyplot as plt
def karplus_strong(x, alpha, M, y_len):
    """
    Synthesizes a new waveform from an existing wavetable, modifies last sample by averaging.
    
    Parameters:
        x (list or nd.array) - initially generated signal
        a (float) - alpha
        M (int) - previous value of y
        y_len (int) - length of output signal
    
    Return:
        np.array - obtained y signal
    
    """
    x = copy.deepcopy(x)
    y = []
    for i in range(y_len):
        if i < M:
            y.insert(i, x[i])
        else:
            y.insert(i, alpha*y[i-M])
    return np.array(y)
def gen_signal_save_output( FS = 16000,
                            range_from = 1,
                           range_to = 10, 
                           x_len = 500,
                           alpha = 0.99,
                           M = 40,
                           path_to_save = '_outputs/'):
    """
    Parameters:
        range_from (int) - start range for random interval
        range_to (int) - end range for random interval
        x_len(int) - length of initial signal to generate
        alpha (float) - decay (or envelop)
        M (int) - previous value of y
        len_y (int) - length of output signal
        path_to_save (string) - relative directory wher wav file will be saved
    
    Returns:
        tuple (pair of x and y, for comparison)
    """
    y_len = FS * 2
    x = np.random.randint(range_from, range_to, x_len).astype(np.float)
    y = karplus_strong(x, alpha, M, y_len)
    wavfile.write(str(path_to_save) + 'y' + '.wav', FS, y)
    
    return y
FS = 16000
y = gen_signal_save_output(FS)
plt.stem(y[0:200]);
Audio(y, rate=FS)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10912425492893169, 'fraction_numerical': 0.013296652911508482, 'mean_word_length': 1.9768076398362893, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '49284', 'license': 'MIT', 'n_tokens_mistral': 756, 'n_tokens_neox': 717, 'n_words': 221, 'path': 'Homeworks/1_Basics_of_DSP/ks_modified.ipynb', 'repo_name': 'lev1khachatryan/ASDS_DSP', 'size': '2181'}