def test_signal_power(): signal1 = nk.signal_simulate(duration=20, frequency=1, sampling_rate=500) pwr1 = nk.signal_power(signal1, [[0.9, 1.6], [1.4, 2.0]], sampling_rate=500) signal2 = nk.signal_simulate(duration=20, frequency=1, sampling_rate=100) pwr2 = nk.signal_power(signal2, [[0.9, 1.6], [1.4, 2.0]], sampling_rate=100) assert np.allclose(np.mean(pwr1.iloc[0] - pwr2.iloc[0]), 0, atol=0.01)
def test_signal_simulate(): # Warning for nyquist criterion with pytest.warns( nk.misc.NeuroKitWarning, match=r"Skipping requested frequency.*cannot be resolved.*" ): nk.signal_simulate(sampling_rate=100, frequency=11, silent=False) # Warning for period duration with pytest.warns( nk.misc.NeuroKitWarning, match=r"Skipping requested frequency.*since its period of.*" ): nk.signal_simulate(duration=1, frequency=0.1, silent=False)
def test_signal_rate(): # since singal_rate wraps signal_period, the latter is tested as well # Test with array. duration = 10 sampling_rate = 1000 signal = nk.signal_simulate(duration=duration, sampling_rate=sampling_rate, frequency=1) info = nk.signal_findpeaks(signal) rate = nk.signal_rate(peaks=info["Peaks"], sampling_rate=1000, desired_length=len(signal)) assert rate.shape[0] == duration * sampling_rate # Test with dictionary.produced from signal_findpeaks. assert info[list(info.keys())[0]].shape == (info["Peaks"].shape[0],) # Test with DataFrame. duration = 120 sampling_rate = 1000 rsp = nk.rsp_simulate( duration=duration, sampling_rate=sampling_rate, respiratory_rate=15, method="sinuosoidal", noise=0 ) rsp_cleaned = nk.rsp_clean(rsp, sampling_rate=sampling_rate) signals, info = nk.rsp_peaks(rsp_cleaned) rate = nk.signal_rate(signals, sampling_rate=sampling_rate, desired_length=duration * sampling_rate) assert rate.shape == (signals.shape[0],) # Test with dictionary.produced from rsp_findpeaks. rate = nk.signal_rate(info, sampling_rate=sampling_rate, desired_length=duration * sampling_rate) assert rate.shape == (duration * sampling_rate,)
def test_signal_rate(): # Test with array. signal = nk.signal_simulate(duration=10, sampling_rate=1000, frequency=1) info = nk.signal_findpeaks(signal) rate = nk.signal_rate(peaks=info["Peaks"], sampling_rate=1000, desired_length=None) assert rate.shape[0] == len(info["Peaks"]) # Test with dictionary.produced from signal_findpeaks. assert info[list(info.keys())[0]].shape == (info["Peaks"].shape[0], ) # Test with DataFrame. rsp = nk.rsp_simulate(duration=120, sampling_rate=1000, respiratory_rate=15, method="sinuosoidal", noise=0) rsp_cleaned = nk.rsp_clean(rsp, sampling_rate=1000) signals, info = nk.rsp_peaks(rsp_cleaned) rate = nk.signal_rate(signals, sampling_rate=1000) assert rate.shape == (signals.shape[0], ) # Test with dictionary.produced from rsp_findpeaks. test_length = 30 rate = nk.signal_rate(info, sampling_rate=1000, desired_length=test_length) assert rate.shape == (test_length, )
def test_signal_distort(): signal = nk.signal_simulate(duration=10, frequency=0.5, sampling_rate=10) # Warning for nyquist criterion with pytest.warns( nk.misc.NeuroKitWarning, match=r"Skipping requested noise frequency.*cannot be resolved.*" ): nk.signal_distort(signal, sampling_rate=10, noise_amplitude=1, silent=False) # Warning for period duration with pytest.warns( nk.misc.NeuroKitWarning, match=r"Skipping requested noise frequency.*since its period of.*" ): signal = nk.signal_simulate(duration=1, frequency=1, sampling_rate=10) nk.signal_distort(signal, noise_amplitude=1, noise_frequency=0.1, silent=False)
def test_signal_plot(): # Test with array signal = nk.signal_simulate(duration=10, sampling_rate=1000) nk.signal_plot(signal, sampling_rate=1000) fig = plt.gcf() for ax in fig.get_axes(): handles, labels = ax.get_legend_handles_labels() assert labels == ['Signal'] assert len(labels) == len(handles) == len([signal]) assert ax.get_xlabel() == 'Time (s)' plt.close(fig) # Test with dataframe data = pd.DataFrame({ "Signal2": np.cos(np.linspace(start=0, stop=20, num=1000)), "Signal3": np.sin(np.linspace(start=0, stop=20, num=1000)), "Signal4": nk.signal_binarize(np.cos(np.linspace(start=0, stop=40, num=1000))) }) nk.signal_plot(data, sampling_rate=None) fig = plt.gcf() for ax in fig.get_axes(): handles, labels = ax.get_legend_handles_labels() assert labels == list(data.columns.values) assert len(labels) == len(handles) == len(data.columns) assert ax.get_xlabel() == 'Samples' plt.close(fig) # Test with list signal = nk.signal_binarize(nk.signal_simulate(duration=10)) phase = nk.signal_phase(signal, method="percents") nk.signal_plot([signal, phase]) fig = plt.gcf() for ax in fig.get_axes(): handles, labels = ax.get_legend_handles_labels() assert labels == ['Signal1', 'Signal2'] assert len(labels) == len(handles) == len([signal, phase]) assert ax.get_xlabel() == 'Samples' plt.close(fig)
def test_signal_timefrequency(): signal = nk.signal_simulate(duration = 50, frequency=5) + 2 * nk.signal_simulate(duration = 50, frequency=20) # short-time fourier transform frequency, time, stft = nk.signal_timefrequency(signal, method="stft", min_frequency=1, max_frequency=50, show=False) assert len(frequency) == stft.shape[0] assert len(time) == stft.shape[1] indices_freq5 = np.logical_and(frequency > 3, frequency < 7) indices_freq20 = np.logical_and(frequency > 18, frequency < 22) assert np.sum(stft[indices_freq5]) < np.sum(stft[indices_freq20]) # wavelet transform frequency, time, cwtm = nk.signal_timefrequency(signal, method="cwt", max_frequency=50, show=False) assert len(frequency) == cwtm.shape[0] assert len(time) == cwtm.shape[1] indices_freq5 = np.logical_and(frequency > 3, frequency < 7) indices_freq20 = np.logical_and(frequency > 18, frequency < 22) assert np.sum(cwtm[indices_freq5]) < np.sum(cwtm[indices_freq20]) # wvd frequency, time, wvd = nk.signal_timefrequency(signal, method="wvd", max_frequency=50, show=False) assert len(frequency) == wvd.shape[0] assert len(time) == wvd.shape[1] indices_freq5 = np.logical_and(frequency > 3, frequency < 7) indices_freq20 = np.logical_and(frequency > 18, frequency < 22) assert np.sum(wvd[indices_freq5]) < np.sum(wvd[indices_freq20]) # pwvd frequency, time, pwvd = nk.signal_timefrequency(signal, method="pwvd", max_frequency=50, show=False) assert len(frequency) == pwvd.shape[0] assert len(time) == pwvd.shape[1] indices_freq5 = np.logical_and(frequency > 3, frequency < 7) indices_freq20 = np.logical_and(frequency > 18, frequency < 22) assert np.sum(pwvd[indices_freq5]) < np.sum(pwvd[indices_freq20])
# Generate 15 seconds of PPG signal (recorded at 250 samples / second) ppg = nk.ppg_simulate(duration=15, sampling_rate=250, heart_rate=70, random_state=333) # Process it #signals, info = nk.ppg_process(emg, sampling_rate=250) # ============================================================================= # Complexity # ============================================================================= # Generate signal signal = nk.signal_simulate(duration=20, sampling_rate=200, noise=0.01) # Find optimal Tau for time-delay embedding optimal_delay = nk.embedding_delay(signal, show=True) # Save plot fig = plt.gcf() fig.set_size_inches(10, 6) fig.savefig("README_embedding.png", dpi=300, h_pad=3) nk.entropy_sample(signal) # ============================================================================= # Statistics # =============================================================================
eog_signal = nk.data("eog_100hz") # Process it signals, info = nk.eog_process(eog_signal, sampling_rate=100) # Plot plot = nk.eog_plot(signals, peaks=info, sampling_rate=100) plot.set_size_inches(10, 6, forward=True) plot.savefig("README_eog.png", dpi=300, h_pad=3) # ============================================================================= # Signal Processing # ============================================================================= # Generate original signal original = nk.signal_simulate(duration=6, frequency=1) # Distort the signal (add noise, linear trend, artifacts etc.) distorted = nk.signal_distort(original, noise_amplitude=0.1, noise_frequency=[5, 10, 20], powerline_amplitude=0.05, artifacts_amplitude=0.3, artifacts_number=3, linear_drift=0.5) # Clean (filter and detrend) cleaned = nk.signal_detrend(distorted) cleaned = nk.signal_filter(cleaned, lowcut=0.5, highcut=1.5) # Compare the 3 signals
# Generate 15 seconds of PPG signal (recorded at 250 samples / second) ppg = nk.ppg_simulate(duration=15, sampling_rate=250, heart_rate=70, random_state=333) # Process it #signals, info = nk.ppg_process(emg, sampling_rate=250) # ============================================================================= # Signal Processing # ============================================================================= # Generate original signal original = nk.signal_simulate(duration=6, frequency=1) # Distort the signal (add noise, linear trend, artifacts etc.) distorted = nk.signal_distort(original, noise_amplitude=0.1, noise_frequency=[5, 10, 20], powerline_amplitude=0.05, artifacts_amplitude=0.3, artifacts_number=3, linear_drift=0.5) # Clean (filter and detrend) cleaned = nk.signal_detrend(distorted) cleaned = nk.signal_filter(cleaned, lowcut=0.5, highcut=1.5) # Compare the 3 signals
# Generate 15 seconds of PPG signal (recorded at 250 samples / second) ppg = nk.ppg_simulate(duration=15, sampling_rate=250, heart_rate=70, random_state=333) # Process it #signals, info = nk.ppg_process(emg, sampling_rate=250) # ============================================================================= # Complexity # ============================================================================= # Generate signal signal = nk.signal_simulate(duration=10, frequency=1, noise=0.01) # Find optimal time delay, embedding dimension and r parameters = nk.complexity_optimize(signal, show=True) parameters # Save plot fig = plt.gcf() plot.set_size_inches(10, 6, forward=True) fig.savefig("README_complexity_optimize.png", dpi=300, h_pad=3) nk.entropy_sample(signal) # ============================================================================= # Statistics # =============================================================================