<jupyter_start><jupyter_text>Aperiodic Signal Visualizer<jupyter_code>%matplotlib inline

import warnings
import collections

import numpy as np
import matplotlib.pyplot as plt

from neurodsp.sim import sim_powerlaw
from neurodsp.plts import plot_power_spectra
from neurodsp.spectral import compute_spectrum
from neurodsp.utils import set_random_seed
import seaborn as sns
sns.set_context('talk')
# Import local code
from code.gif import clear_output, _gif_plot_output
#from code.utils import yield_sig<jupyter_output><empty_output><jupyter_text>Settings<jupyter_code># Set random seed
set_random_seed(505)<jupyter_output><empty_output><jupyter_text>Functions<jupyter_code>def build_plot(sigs, plot_func, *args, sleep=0.05, n_build=25):
    
    yielders = [yield_sig(sig) for sig in sigs]
    
    data = collections.defaultdict(list)
    
    for ind in range(n_build):
        
        clear_output(wait=True)
        
        for ind, yielder in enumerate(yielders):
            data[ind].append(next(yielder))
        
        plot_func(data)
        
        _gif_plot_output(plt.gcf(), False, ind, sleep=sleep)
def yield_sig(sig, step=1):
    for el in sig[::step]:
        yield el
def plot_ts(data_dict, ax=None):
    """Plot timeseries."""
    
    if not ax:
        _, ax = plt.subplots()
    
    for label, data in data_dict.items():
        ax.plot(data, label=label)

    ax.set(xticks=[], yticks=[]);        
    plt.grid(True)
    
    
def plot_hist(data_dict, ax=None):
    """Plot histogram."""
    
    if not ax:
        _, ax = plt.subplots()
    
    for label, data in data_dict.items():
        ax.hist(data, label=label, alpha=0.5)

    ax.set(xticks=[], yticks=[]);
    plt.grid(True)
    
    
def plot_spectrum(data_dict, ax=None):
    """Plot spectrum."""
    
    if not ax:
        _, ax = plt.subplots()
    
    for label, data in data_dict.items():  
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            freqs, powers = compute_spectrum(np.array(data), fs=fs)
            ax.plot(np.log(freqs), np.log(powers))
            #ax.loglog(freqs, powers)
            #plot_power_spectra(freqs, powers, ax=ax)
            ax.set(xticks=[], yticks=[]);
def make_axes():
    """Make axes for combined plot.
    
    Notes:
    Placement definitions: Left, Bottom, Width, Height
    """
    
    fig = plt.figure()
    ax1 = fig.add_axes([0.0, 0.6, 1.3, 0.5])
    ax2 = fig.add_axes([0.0, 0.0, 0.6, 0.5])
    ax3 = fig.add_axes([0.7, 0.0, 0.6, 0.5]) 
    
    return fig, [ax1, ax2, ax3]
def build_all(sigs, n_build=np.inf, sleep=0.05, save=False):
    """Build all plots together."""
    
    yielders = [yield_sig(sig) for sig in sigs]
    
    data = collections.defaultdict(list)

    for ind in range(n_build):
        
        clear_output(wait=True)

        fig, axes = make_axes()
        
        for ind, yielder in enumerate(yielders):
            data[ind].append(next(yielder))
        
        plot_ts(data, ax=axes[0])
        plot_hist(data, ax=axes[1])
        plot_spectrum(data, ax=axes[2])
        
        _gif_plot_output(fig, save, ind, label='02_ap_sig', sleep=sleep)<jupyter_output><empty_output><jupyter_text>Simulate Data<jupyter_code>n_seconds = 10
fs = 100
sig1 = sim_powerlaw(n_seconds, fs, 0)
sig2 = sim_powerlaw(n_seconds, fs, -1)
sig3 = sim_powerlaw(n_seconds, fs, -2)
yielder1 = yield_sig(sig1)
yielder2 = yield_sig(sig2)
yielder3 = yield_sig(sig3)
build_plot([sig1, sig2], plot_ts)
build_plot([sig1, sig2], plot_hist)
build_plot([sig1, sig2], plot_spectrum, n_build=100)<jupyter_output><empty_output><jupyter_text>Create visualizer with all panels<jupyter_code>build_all([sig2], n_build=250, sleep=0.01)
build_all([sig2, sig3], n_build=250, sleep=0.01)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12803590285110877, 'fraction_numerical': 0.02375923970432946, 'mean_word_length': 3.159165751920966, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 21, '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': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '501759', 'license': 'MIT', 'n_tokens_mistral': 1446, 'n_tokens_neox': 1370, 'n_words': 283, 'path': 'notebooks/02-aperiodic_signals.ipynb', 'repo_name': 'TomDonoghue/SigViz', 'size': '3788'}