Denoising Notebook

In [1]:
import argparse
import time
import brainflow
import numpy as np

import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds
from brainflow.data_filter import DataFilter, AggOperations, WaveletTypes, NoiseEstimationLevelTypes, WaveletExtensionTypes, ThresholdTypes, WaveletDenoisingTypes
In [2]:
# use synthetic board for demo
params = BrainFlowInputParams()
board_id = BoardIds.SYNTHETIC_BOARD.value
board = BoardShim(board_id, params)
board.prepare_session()
board.start_stream()
time.sleep(10)
data = board.get_current_board_data(500)
board.stop_stream()
board.release_session()
[2022-09-19 09:17:57.761] [board_logger] [info] incoming json: {
    "file": "",
    "ip_address": "",
    "ip_port": 0,
    "ip_protocol": 0,
    "mac_address": "",
    "master_board": -100,
    "other_info": "",
    "preset": 0,
    "serial_number": "",
    "serial_port": "",
    "timeout": 0
}
In [3]:
# plot original data
eeg_channels = BoardShim.get_eeg_channels(board_id)
df = pd.DataFrame(np.transpose(data))
df[eeg_channels].plot(subplots=True)
plt.show()
/home/docs/checkouts/readthedocs.org/user_builds/brainflow/envs/master/lib/python3.7/site-packages/traitlets/traitlets.py:3284: FutureWarning: --rc={'figure.dpi': 96} for dict-traits is deprecated in traitlets 5.0. You can pass --rc <key=value> ... multiple times to add items to a dict.
  FutureWarning,
../_images/notebooks_denoising_3_1.svg
In [4]:
# demo for denoising, apply different methods to different channels for demo
for count, channel in enumerate(eeg_channels):
    # first of all you can try simple moving median or moving average with different window size
    if count == 0:
        DataFilter.perform_rolling_filter(data[channel], 3, AggOperations.MEAN.value)
    elif count == 1:
        DataFilter.perform_rolling_filter(data[channel], 3, AggOperations.MEDIAN.value)
    # if methods above dont work for your signal you can try wavelet based denoising
    # feel free to try different parameters
    else:
        DataFilter.perform_wavelet_denoising(data[channel], WaveletTypes.BIOR3_9, 3, WaveletDenoisingTypes.SURESHRINK, ThresholdTypes.HARD,
                                                 WaveletExtensionTypes.SYMMETRIC, NoiseEstimationLevelTypes.FIRST_LEVEL)
In [5]:
# plot denoised data
df = pd.DataFrame(np.transpose(data))
df[eeg_channels].plot(subplots=True)
plt.show()
../_images/notebooks_denoising_5_0.svg