def NoiseRemoval( self, df, valuecol="distance", samplinginterval=5,…
- User
def Noise_Removal( self, df, value_col="distance", sampling_interval=5, cutoff_frequency=0.05, filter_order=4, to_plot_graphs=True, date_range=["2024-07-21", "2024-07-22"], ): """ Cleans and processes time series data by removing outliers, applying STL decomposition, filtering, and calculating the Power Spectral Density (PSD).
This method: 1. Applies STL decomposition to remove outliers. 2. Replaces NaN values in the cleaned data. 3. Applies a Butterworth lowpass filter to the cleaned data. 4. Calculates and optionally plots the PSD of the original and cleaned signals. 5. Optionally plots the original, no-outlier, and filtered signals. Parameters: df (pd.DataFrame): DataFrame containing the time series data. value_col (str): Name of the column containing the values. period (int): Periodicity in the data for STL decomposition. seasonal (int): Length of the seasonal component for STL decomposition. 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. Returns: pd.DataFrame: DataFrame with the cleaned and filtered data. """ df = df.copy() # Calculate sampling rate sampling_rate = 1 / sampling_interval # Hz # Calculate the PSD of the original signal freqs, psd = self.calculate_psd(df[value_col], sampling_rate) # Apply Butterworth filter on the cleaned data df["filtered_distance"] = self.butter_lowpass_filter( df["distance"], cutoff_frequency, sampling_rate, filter_order ) if to_plot_graphs: # Plot the PSD of the original signal plt.figure(figsize=(14, 7)) plt.semilogy(freqs, psd) plt.title("Power Spectral Density (PSD) of the Original Signal") plt.xlabel("Frequency (Hz)") plt.ylabel("Power/Frequency (dB/Hz)") plt.show() # Interactive plot with Plotly start_date, end_date = date_range trace1 = go.Scatter( x=df[start_date:end_date].index, y=df["distance"][start_date:end_date], mode="lines", name="Original Signal", ) trace3 = go.Scatter( x=df[start_date:end_date].index, y=df["filtered_distance"][start_date:end_date], mode="lines", name="Filtered Signal", line=dict(color="red"), ) layout = go.Layout( title="Signal Before and After Filtering", xaxis=dict(title="Sample Number"), yaxis=dict(title="Distance"), legend=dict(x=0, y=1), ) fig = go.Figure(data=[trace1, trace3], layout=layout) fig.show() df_clean = df.drop(columns=["distance"]) df_clean.rename(columns={"filtered_distance": "distance"}, inplace=True) return df_clean, dfcalculate the 10 % point of amplitude in the y axis of plot from higest to lowest of psd plot and print the 10% point . for example if the higest point is 100000 and lowest is 1000 then 100000-1000 = 99000 then 10 % of 99000 is 9900 . also print the x-axis frequency value at 10 % point . draw the line of 10% and intersection at x-axis line in the plot
- Assistant
To achieve the desired functionality—calculating the 10% amplitude point of the PSD, printing its value along with the corresponding frequency, and visualizing these on the PSD plot—you can modify your
Noise_Removalmethod as follows:-
Calculate the 10% Amplitude Point:
- Determine the highest and lowest PSD values.
- Compute the 10% difference.
- Find the 10% amplitude level (
threshold).
-
Find the Corresponding Frequency:
- Identify the frequency where the PSD first exceeds the 10% threshold.
-
Plot the Horizontal Line and Intersection Point:
- Draw a horizontal line at the 10% amplitude level.
- Mark the intersection point on the PSD plot.
-
Print the Calculated Values:
- Display the 10% amplitude point and its corresponding frequency.
Here's the modified
Noise_Removalmethod incorporating these changes:import pandas as pd import matplotlib.pyplot as plt import plotly.graph_objs as go from scipy.signal import butter, filtfilt def Noise_Removal( self, df, value_col="distance", sampling_interval=5, cutoff_frequency=0.05, filter_order=4, to_plot_graphs=True, date_range=["2024-07-21", "2024-07-22"], ): """ Cleans and processes time series data by removing outliers, applying STL decomposition, filtering, and calculating the Power Spectral Density (PSD). This method: 1. Applies STL decomposition to remove outliers. 2. Replaces NaN values in the cleaned data. 3. Applies a Butterworth lowpass filter to the cleaned data. 4. Calculates and optionally plots the PSD of the original and cleaned signals. 5. Optionally plots the original, no-outlier, and filtered signals. 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): List containing start and end dates for plotting. Returns: pd.DataFrame: DataFrame with the cleaned and filtered data. """ import numpy as np df = df.copy() # Calculate sampling rate sampling_rate = 1 / sampling_interval # Hz # Calculate the PSD of the original signal freqs, psd = self.calculate_psd(df[value_col], sampling_rate) # Calculate 10% amplitude point psd_max = np.max(psd) psd_min = np.min(psd) amplitude_range = psd_max - psd_min threshold = psd_min + 0.10 * amplitude_range # 10% point # Find the frequency where PSD first exceeds the threshold freq_at_threshold = freqs[np.argmax(psd >= threshold)] if np.any(psd >= threshold) else None # Print the 10% point and corresponding frequency print(f"10% Amplitude Point: {threshold}") if freq_at_threshold is not None: print(f"Frequency at 10% Amplitude Point: {freq_at_threshold} Hz") else: print("No frequency found where PSD exceeds the 10% amplitude threshold.") # Apply Butterworth filter on the cleaned data df["filtered_distance"] = self.butter_lowpass_filter( df[value_col], cutoff_frequency, sampling_rate, filter_order ) if to_plot_graphs: # Plot the PSD of the original signal plt.figure(figsize=(14, 7)) plt.semilogy(freqs, psd, label='Original PSD') # Draw horizontal line at 10% amplitude point plt.axhline(y=threshold, color='r', linestyle='--', label='10% Amplitude Threshold') # If a frequency at threshold exists, plot the intersection point if freq_at_threshold is not None: plt.plot(freq_at_threshold, threshold, 'ro') # Red dot plt.text(freq_at_threshold, threshold, f' ({freq_at_threshold:.2f} Hz, {threshold:.2f})', verticalalignment='bottom', color='red') plt.title("Power Spectral Density (PSD) of the Original Signal") plt.xlabel("Frequency (Hz)") plt.ylabel("Power/Frequency (dB/Hz)") plt.legend() plt.show() # Interactive plot with Plotly start_date, end_date = date_range trace1 = go.Scatter( x=df[start_date:end_date].index, y=df[value_col][start_date:end_date], mode="lines", name="Original Signal", ) trace3 = go.Scatter( x=df[start_date:end_date].index, y=df["filtered_distance"][start_date:end_date], mode="lines", name="Filtered Signal", line=dict(color="red"), ) layout = go.Layout( title="Signal Before and After Filtering", xaxis=dict(title="Sample Number"), yaxis=dict(title="Distance"), legend=dict(x=0, y=1), ) fig = go.Figure(data=[trace1, trace3], layout=layout) fig.show() df_clean = df.drop(columns=[value_col]) df_clean.rename(columns={"filtered_distance": value_col}, inplace=True) return df_clean, dfDetailed Explanation of the Modifications:
-
Import Necessary Libraries:
- Added
import numpy as npwithin the method to ensure NumPy functions are available.
- Added
-
Calculate the 10% Amplitude Point:
psd_max = np.max(psd) psd_min = np.min(psd) amplitude_range = psd_max - psd_min threshold = psd_min + 0.10 * amplitude_range # 10% pointpsd_max: The maximum value in the PSD.psd_min: The minimum value in the PSD.amplitude_range: The difference between the maximum and minimum PSD values.threshold: The 10% amplitude point calculated aspsd_min + 10% of the range.
-
Find the Corresponding Frequency:
freq_at_threshold = freqs[np.argmax(psd >= threshold)] if np.any(psd >= threshold) else Nonenp.argmax(psd >= threshold): Returns the index of the first occurrence where PSD exceeds or equals the threshold.freq_at_threshold: The frequency corresponding to the 10% amplitude point.- If no PSD values exceed the threshold,
freq_at_thresholdis set toNone.
-
Print the Calculated Values:
print(f"10% Amplitude Point: {threshold}") if freq_at_threshold is not None: print(f"Frequency at 10% Amplitude Point: {freq_at_threshold} Hz") else: print("No frequency found where PSD exceeds the 10% amplitude threshold.")- Outputs the 10% amplitude value and its corresponding frequency to the console.
-
Enhance the PSD Plot with the 10% Line and Intersection:
# Draw horizontal line at 10% amplitude point plt.axhline(y=threshold, color='r', linestyle='--', label='10% Amplitude Threshold') # If a frequency at threshold exists, plot the intersection point if freq_at_threshold is not None: plt.plot(freq_at_threshold, threshold, 'ro') # Red dot plt.text(freq_at_threshold, threshold, f' ({freq_at_threshold:.2f} Hz, {threshold:.2f})', verticalalignment='bottom', color='red')plt.axhline: Draws a horizontal dashed red line at the 10% amplitude threshold.plt.plot: Marks the intersection point with a red dot.plt.text: Annotates the intersection point with its frequency and amplitude values.
-
Update the Docstring:
- Corrected the
periodandseasonalparameters, which were not used in the provided method, by removing them from the parameter description.
- Corrected the
Additional Recommendations:
-
Error Handling: Ensure that the
calculate_psdandbutter_lowpass_filtermethods are properly defined within your class. Handle cases where the DataFrame might not contain the specifiedvalue_col. -
Visualization Enhancements: Depending on your data, you might want to adjust the plot's aesthetics for better clarity, such as setting appropriate limits or using log scales where necessary.
-
Parameter Validation: Validate input parameters (e.g.,
sampling_interval,cutoff_frequency) to ensure they are within acceptable ranges to prevent runtime errors.
Example Usage:
Assuming you have a class
SignalProcessorthat contains theNoise_Removalmethod along with the requiredcalculate_psdandbutter_lowpass_filtermethods:import pandas as pd # Example DataFrame data = { 'timestamp': pd.date_range(start='2024-07-21', periods=1000, freq='S'), 'distance': np.random.normal(loc=0, scale=1, size=1000).cumsum() } df = pd.DataFrame(data).set_index('timestamp') # Instantiate the processor and apply noise removal processor = SignalProcessor() df_clean, df_processed = processor.Noise_Removal( df, value_col="distance", sampling_interval=1, # Sampling interval in seconds cutoff_frequency=0.05, filter_order=4, to_plot_graphs=True, date_range=["2024-07-21", "2024-07-22"], )This will process the
dfDataFrame, calculate and plot the PSD with the 10% amplitude threshold, and output the cleaned DataFramedf_clean. The console will display the 10% amplitude point and the corresponding frequency. -