Python Vibration Analysis
Python Vibration Analysis
Vibration Analysts:
A Beginner's Guide
Introduction
Welcome to the world of Python for vibration analysis! If you're used to spreadsheets
or specialized software, you might wonder why you should learn Python. Python is a
versatile, powerful, and free programming language with a vast ecosystem of libraries
specifically designed for scientific computing, data analysis, and visualization.
# Arithmetic
total_samples = sampling_rate * duration_seconds
print("Total Samples:", total_samples)
# String concatenation
location = "North Plant"
full_id = location + " - " + sensor_name
print(full_id)
temperature = 75 # degrees C
if temperature > 80:
print("ALERT: High Temperature!")
elif temperature > 65:
print("WARNING: Elevated Temperature.")
else:
print("Temperature OK.")
2.5 Functions
Functions are reusable blocks of code. You define them with def and call them by
name.
Now you can use functions from these libraries, e.g., np.array(), pd.read_csv(),
plt.plot().
### 4.2 Creating Scatter Plots
# Useful for comparing two variables
plt.figure(figsize=(7, 6))
plt.scatter(plot_df['Amplitude_g'], plot_df['Amplitude_Related'], alpha=0.5, s=10) #
s=size, alpha=transparency
plt.xlabel("Amplitude (g)")
plt.ylabel("Related Amplitude")
plt.title("Scatter Plot: Amplitude vs Related Amplitude")
plt.grid(True)
plt.tight_layout()
plt.show()
### 4.3 Understanding and Visualizing Correlation
Correlation measures the linear relationship between two variables (-1 to +1). Pandas
DataFrames have a built-in `.corr()` method.
# Calculate the correlation matrix
correlation_matrix = plot_df[['Amplitude_g', 'Amplitude_Related', 'Temperature']].corr()
print("\nCorrelation Matrix:")
print(correlation_matrix)
# Visualize the correlation matrix using Seaborn's heatmap
plt.figure(figsize=(7, 6))
sns.heatmap(correlation_matrix, annot=True, cmap='coolwarm', fmt=".2f")
# annot=True: show values on heatmap
# cmap='coolwarm': color map choice
# fmt=".2f": format numbers to 2 decimal places
plt.title("Correlation Matrix Heatmap")
plt.tight_layout()
plt.show()
Key Matplotlib Concepts:
● plt.figure(): Creates a new figure window. figsize controls its size.
● plt.plot(x, y): Creates a line plot.
● plt.scatter(x, y): Creates a scatter plot.
● plt.xlabel(), plt.ylabel(), plt.title(): Set labels and title.
● plt.legend(): Displays the legend (requires label='...' in plot commands).
● plt.grid(): Adds a grid.
● plt.tight_layout(): Adjusts spacing.
● plt.show(): Displays the plot(s). In Jupyter notebooks, plots often appear
automatically, but plt.show() is good practice.
● plt.savefig('filename.png'): Saves the current figure to a file (call before
plt.show()).
Seaborn: Builds on Matplotlib, providing higher-level functions for attractive
statistical plots like heatmaps (sns.heatmap), distribution plots (sns.histplot,
sns.kdeplot), and more.
1. Get Time Data: You need your vibration signal (signal) and the sampling_rate.
2. Compute FFT: Use scipy.fft.fft(signal).
3. Compute Frequencies: Use scipy.fft.fftfreq(n_samples, 1 / sampling_rate).
4. Get Positive Frequencies: The FFT output is mirrored; usually, you only need the
first half (positive frequencies).
5. Calculate Amplitude: Take the absolute value (np.abs()) of the positive
frequency FFT results. Normalize by the number of samples (n_samples) and
multiply by 2 (except the 0 Hz component) to get meaningful amplitude units
corresponding to the original signal.
6. Plot: Plot the calculated amplitude against the positive frequencies.
Interpretation: Peaks in the FFT plot indicate the frequencies with the most energy in
the signal. These often correspond to machine running speeds, bearing defect
frequencies, gear mesh frequencies, resonance, etc. The height of the peak relates to
the intensity of vibration at that frequency.
# You could then perform FFT on the 'filtered_signal'
# to see the effect in the frequency domain.
Note: Filter design is a complex topic. Always validate your filter's effect (e.g., by
checking its frequency response using scipy.signal.sosfreqz) and understand its
impact on phase.