To calculate the 5th percentile (5% point) of your data to represent noise and remove it, you can integrate this functionality into your existing Noise_Removal method. The 5th percentile can help identify the lower tail of your data distribution, which you can treat as noise and either remove or adjust accordingly.
Below is an enhanced version of your Noise_Removal method that includes the calculation of the 5th percentile and removes noise based on this threshold. Additionally, I’ve made some improvements and fixes to your existing code, such as ensuring the threshold_percent parameter is utilized and handling date ranges correctly for plotting.
Updated Noise_Removal Method
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.graph_objs as go
from scipy.signal import butter, filtfilt, welch
class SignalProcessor:
def calculate_psd(self, signal, sampling_rate):
"""
Calculate the Power Spectral Density (PSD) of a signal using Welch's method.
Parameters:
signal (pd.Series): The input signal.
sampling_rate (float): Sampling rate in Hz.
Returns:
freqs (ndarray): Array of sample frequencies.
psd (ndarray): Power spectral density of the signal.
"""
freqs, psd = welch(signal, fs=sampling_rate, nperseg=1024)
return freqs, psd
def butter_lowpass_filter(self, data, cutoff, fs, order):
"""
Apply a Butterworth lowpass filter to the data.
Parameters:
data (pd.Series): The input data to filter.
cutoff (float): The cutoff frequency in Hz.
fs (float): Sampling rate in Hz.
order (int): The order of the filter.
Returns:
filtered_data (ndarray): The filtered data.
"""
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
filtered_data = filtfilt(b, a, data)
return filtered_data
def Noise_Removal(
self,
df,
value_col="distance",
sampling_interval=5,
cutoff_frequency=0.05,
filter_order=4,
to_plot_graphs=True,
date_range=None, # Changed default to None for flexibility
threshold_percent=0.05,
):
"""
Cleans and processes time series data by removing noise based on the 5th percentile,
applying a Butterworth lowpass filter, and optionally plotting the results.
Parameters:
df (pd.DataFrame): DataFrame containing the time series data.
value_col (str): Name of the column containing the values.
sampling_interval (float): Time interval between consecutive data points (in seconds).
cutoff_frequency (float): The cutoff frequency for the Butterworth filter.
filter_order (int): The order of the Butterworth filter.
to_plot_graphs (bool): Whether to plot the graphs or not.
date_range (list or tuple): [start_date, end_date] for plotting. Should be in a format recognizable by pandas.
threshold_percent (float): The percentile below which data is considered noise (e.g., 0.05 for 5%).
Returns:
pd.DataFrame: DataFrame with the cleaned and filtered data.
"""
df = df.copy()
# Ensure the DataFrame index is datetime
if not isinstance(df.index, pd.DatetimeIndex):
raise ValueError("The DataFrame index must be a DateTimeIndex.")
# Calculate sampling rate
sampling_rate = 1 / sampling_interval # Hz
# Calculate the 5th percentile threshold
threshold = df[value_col].quantile(threshold_percent)
print(f"5th Percentile Threshold for '{value_col}': {threshold}")
# Remove noise by setting values below the threshold to NaN
df['cleaned_distance'] = df[value_col].where(df[value_col] > threshold, np.nan)
# Optionally, interpolate to fill NaN values
df['cleaned_distance'].interpolate(method='linear', inplace=True)
# Calculate the PSD of the original signal
freqs, psd = self.calculate_psd(df[value_col], sampling_rate)
# Calculate the PSD of the cleaned signal
freqs_clean, psd_clean = self.calculate_psd(df['cleaned_distance'], sampling_rate)
# Apply Butterworth filter on the cleaned data
df["filtered_distance"] = self.butter_lowpass_filter(
df['cleaned_distance'], cutoff_frequency, sampling_rate, filter_order
)
if to_plot_graphs:
# Plot the PSD of the original and cleaned signals
plt.figure(figsize=(14, 7))
plt.semilogy(freqs, psd, label="Original PSD")
plt.semilogy(freqs_clean, psd_clean, label="Cleaned PSD")
plt.title("Power Spectral Density (PSD) of the Original and Cleaned Signals")
plt.xlabel("Frequency (Hz)")
plt.ylabel("Power/Frequency (dB/Hz)")
plt.legend()
plt.show()
# Interactive plot with Plotly
if date_range is not None and len(date_range) == 2:
start_date, end_date = pd.to_datetime(date_range)
mask = (df.index >= start_date) & (df.index <= end_date)
df_plot = df.loc[mask]
trace1 = go.Scatter(
x=df_plot.index,
y=df_plot[value_col],
mode="lines",
name="Original Signal",
)
trace2 = go.Scatter(
x=df_plot.index,
y=df_plot['cleaned_distance'],
mode="lines",
name="Cleaned Signal",
line=dict(color="orange"),
)
trace3 = go.Scatter(
x=df_plot.index,
y=df_plot["filtered_distance"],
mode="lines",
name="Filtered Signal",
line=dict(color="red"),
)
layout = go.Layout(
title="Signal Before and After Noise Removal and Filtering",
xaxis=dict(title="Time"),
yaxis=dict(title="Distance"),
legend=dict(x=0, y=1),
)
fig = go.Figure(data=[trace1, trace2, trace3], layout=layout)
fig.show()
else:
print("Date range not provided or invalid. Skipping interactive Plotly graph.")
# Prepare the cleaned DataFrame to return
df_clean = df[['filtered_distance']].rename(columns={"filtered_distance": value_col})
return df_clean, df
# Example Usage
if __name__ == "__main__":
# Sample data creation
rng = pd.date_range(start='2024-07-21', end='2024-07-22', freq='5S')
np.random.seed(0)
# Simulate a signal with noise
signal = np.sin(2 * np.pi * 0.01 * np.arange(len(rng))) + np.random.normal(0, 0.5, len(rng))
df = pd.DataFrame({'distance': signal}, index=rng)
processor = SignalProcessor()
df_clean, df_full = processor.Noise_Removal(
df,
value_col="distance",
sampling_interval=5, # seconds
cutoff_frequency=0.05, # Hz
filter_order=4,
to_plot_graphs=True,
date_range=["2024-07-21", "2024-07-22"],
threshold_percent=0.05, # 5%
)
print(df_clean.head())
Explanation of Updates
-
Calculating the 5th Percentile Threshold:
-
Removing Noise Based on Threshold:
- Data points below the 5th percentile are considered noise. These points are set to
NaN in a new column cleaned_distance.
-
df['cleaned_distance'] = df[value_col].where(df[value_col] > threshold, np.nan)
- To maintain continuity in the data, you can interpolate these
NaN values. Here, linear interpolation is used, but you can choose other methods based on your data characteristics.
-
df['cleaned_distance'].interpolate(method='linear', inplace=True)
-
Power Spectral Density (PSD) Calculation:
- PSD is calculated for both the original and cleaned signals to visualize the effect of noise removal.
- This helps in understanding how much noise has been removed in the frequency domain.
-
Butterworth Lowpass Filter:
- After cleaning the data based on the 5th percentile, a Butterworth lowpass filter is applied to further smooth the signal.
- The cutoff frequency and filter order can be adjusted as needed.
-
Plotting:
- PSD Plot: Both original and cleaned PSDs are plotted to visualize the noise removal effect in the frequency domain.
- Interactive Plotly Graph: An interactive graph shows the original, cleaned, and filtered signals over the specified date range.
- The date range is now handled more robustly, ensuring that it is a list or tuple with two elements representing the start and end dates.
-
Error Handling:
- The method checks if the DataFrame index is a
DateTimeIndex to ensure that time-based operations work correctly.
- It also validates the
date_range parameter before attempting to plot the interactive graph.
-
Returning Cleaned Data:
Additional Notes
-
STL Decomposition: Your original docstring mentioned STL decomposition to remove outliers, but the provided code did not include this step. If STL decomposition is required, you can integrate it using the statsmodels library before applying the percentile-based noise removal.
-
Parameter Tuning: The cutoff_frequency, filter_order, and threshold_percent parameters are crucial and may require tuning based on your specific dataset and noise characteristics.
-
Handling Edge Cases: Ensure that after removing noise and interpolating, the signal remains meaningful for your application. In some cases, aggressive noise removal might distort the genuine signal.
-
Visualization: Always inspect the plots to verify that noise removal is performing as expected. Adjust parameters as necessary based on visual feedback.
Conclusion
By integrating the 5th percentile threshold into your noise removal pipeline, you can effectively identify and eliminate low-intensity noise from your data. The updated method provides a comprehensive approach by combining statistical thresholding with frequency-based filtering, ensuring a cleaner and more reliable signal for subsequent analysis.