Sure! Below is a Python script that calculates the road profile and the International Roughness Index (IRI) based on measured sprung and unsprung accelerations of a running car. The script calculates the overall IRI, as well as IRI values for 20-meter and 100-meter sections.
Overview
-
Inputs Required:
- Sprung Accelerations (
sprung_acc): NumPy array of sprung accelerations measured in m/s².
- Unsprung Accelerations (
unsprung_acc): NumPy array of unsprung accelerations measured in m/s².
- Sampling Rate (
fs): Sampling rate of the accelerometer data (default is 800 Hz).
- Vehicle Speed (
speed): The constant speed at which the vehicle was traveling (in m/s).
-
Steps Involved:
- Integration of Accelerations: To obtain velocity and displacement from the acceleration data.
- Road Profile Calculation: Using unsprung acceleration to derive the road profile.
- IRI Calculation: Compute the IRI over the total distance as well as over 20m and 100m segments.
-
Assumptions:
- The vehicle speed is constant.
- Initial displacement and velocity are zero.
- The script uses numerical integration (cumulative trapezoidal) to estimate displacement.
- No filtering is applied to the acceleration data. Depending on your data quality, you might want to apply filters to remove noise before integration.
Dependencies
Make sure you have the following Python packages installed:
You can install them using pip:
pip install numpy scipy matplotlib
The Python Script
import numpy as np
from scipy.integrate import cumtrapz
from scipy.signal import butter, filtfilt
import matplotlib.pyplot as plt
def butter_lowpass(cutoff, fs, order=4):
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='low', analog=False)
return b, a
def filter_signal(data, cutoff, fs, order=4):
b, a = butter_lowpass(cutoff, fs, order=order)
y = filtfilt(b, a, data)
return y
def calculate_iri(unsprung_acc, fs, speed, window_lengths=[20, 100]):
"""
Calculate IRI based on unsprung acceleration.
Parameters:
- unsprung_acc: numpy array of unsprung acceleration data (m/s²)
- fs: Sampling frequency (Hz)
- speed: Vehicle speed (m/s)
- window_lengths: List of window lengths in meters for segment-wise IRI
Returns:
- iri_overall: Overall IRI (m/km)
- iri_segments: Dictionary with window lengths as keys and IRI arrays as values
- distance: Distance array corresponding to the IRI segments
"""
# Time array
dt = 1.0 / fs
t = np.arange(len(unsprung_acc)) * dt
# Integrate acceleration to get velocity (assuming initial velocity = 0)
# Here, we assume the acceleration is purely due to road profile; in reality, vehicle dynamics may need to be considered
velocity = cumtrapz(unsprung_acc, dx=dt, initial=0)
# Integrate velocity to get displacement (road profile z)
# Assuming initial displacement = 0
displacement = cumtrapz(velocity, dx=dt, initial=0)
# Calculate distance x based on vehicle speed
x = speed * t # in meters
# To compute dz/dx, we need to compute derivative of displacement with respect to distance
# dz/dx = (dz/dt) / (dx/dt) = vz / v = velocity / speed
dz_dx = velocity / speed # unitless
# Compute absolute slope
abs_dz_dx = np.abs(dz_dx)
# Compute overall IRI
total_distance = x[-1] # in meters
iri_overall = (np.sum(abs_dz_dx) / total_distance) * 1000 # Convert to m/km
# Compute IRI for specified window lengths
iri_segments = {}
for window in window_lengths:
num_samples_per_window = int(window / (speed * dt))
if num_samples_per_window < 1:
raise ValueError(f"Window length {window} m is too small for the given speed and sampling rate.")
# Number of complete windows
num_windows = len(abs_dz_dx) // num_samples_per_window
# Truncate the data to have complete windows
truncated_length = num_windows * num_samples_per_window
truncated_iri = abs_dz_dx[:truncated_length]
# Reshape and compute IRI per window
reshaped = truncated_iri.reshape((num_windows, num_samples_per_window))
iri_per_window = (reshaped.sum(axis=1) / window) * 1000 # m/km
iri_segments[window] = iri_per_window
return iri_overall, iri_segments, x, displacement
def main():
# Example usage
# For real application, replace these with actual data loading mechanisms
fs = 800 # Sampling rate in Hz
speed_kmh = 60 # Vehicle speed in km/h
speed = speed_kmh / 3.6 # Convert to m/s
duration = 60 # seconds
t = np.arange(0, duration, 1/fs)
# Simulate unsprung acceleration data (replace with actual measurements)
# Example: road profile inducing vibrations
# Here, we'll simulate a simple sinusoidal road with some frequency
road_freq = 2 # Hz
road_amplitude = 0.05 # m/s²
unsprung_acc = road_amplitude * np.sin(2 * np.pi * road_freq * t)
# Optional: Add some noise
noise = 0.01 * np.random.randn(len(t))
unsprung_acc += noise
# Optional: Filter the acceleration signal to remove high-frequency noise
cutoff = 20 # Hz, adjust as needed
unsprung_acc = filter_signal(unsprung_acc, cutoff, fs)
# Calculate IRI
iri_overall, iri_segments, distance, displacement = calculate_iri(
unsprung_acc, fs, speed, window_lengths=[20, 100]
)
print(f"Overall IRI: {iri_overall:.3f} m/km")
for window, iri_values in iri_segments.items():
avg_iri = np.mean(iri_values)
print(f"Average IRI over {window} m segments: {avg_iri:.3f} m/km")
# Optionally, plot the IRI distribution
plt.figure()
window_distances = np.arange(len(iri_values)) * window / 1000 # in km
plt.plot(window_distances, iri_values)
plt.xlabel('Distance (km)')
plt.ylabel('IRI (m/km)')
plt.title(f'IRI over {window} m Segments')
plt.grid(True)
plt.show()
# Plot Road Profile
plt.figure(figsize=(10, 4))
plt.plot(distance, displacement)
plt.xlabel('Distance (m)')
plt.ylabel('Road Profile Displacement (m)')
plt.title('Estimated Road Profile')
plt.grid(True)
plt.show()
# Plot IRI Segments histograms
for window, iri_values in iri_segments.items():
plt.figure()
plt.hist(iri_values, bins=50, edgecolor='k')
plt.xlabel('IRI (m/km)')
plt.ylabel('Frequency')
plt.title(f'IRI Distribution for {window} m Segments')
plt.grid(True)
plt.show()
if __name__ == "__main__":
main()
Explanation of the Script
-
Filtering (Optional but Recommended):
- High-frequency noise in acceleration data can significantly affect the numerical integration, leading to drift and inaccurate displacement estimates.
- A Butterworth low-pass filter is applied to the unsprung acceleration data to remove frequencies above a certain cutoff (e.g., 20 Hz). Adjust the
cutoff frequency based on your data characteristics.
-
Integration to Get Velocity and Displacement:
- Velocity (
v) is obtained by integrating the acceleration data over time.
- Displacement (
z) is obtained by integrating the velocity data over time.
- Both integrations assume zero initial conditions (initial velocity and displacement are zero).
-
Road Profile Calculation:
- The road profile (
z) represents the vertical displacement of the road. It's derived from the unsprung acceleration because unsprung mass (like wheels and suspension) directly interacts with the road surface.
-
IRI Calculation:
- Overall IRI: Calculated by summing the absolute slope (
|dz/dx|) across the entire distance and normalizing it per kilometer.
- Segment-wise IRI (20m and 100m): The data is divided into segments of specified lengths, and IRI is calculated for each segment to analyze the roughness over these individual sections.
-
Plotting:
- The script plots the estimated road profile and the distribution of IRI values for both 20m and 100m segments. These visualizations help in understanding the road roughness and its variability.
-
Simulated Data for Demonstration:
- For demonstration purposes, the script simulates unsprung acceleration data as a sinusoidal signal. In practical scenarios, replace this simulated data with actual measured acceleration data from your sensors.
Usage Instructions
-
Replace Simulated Data with Actual Measurements:
- Load your actual
unsprung_acc and sprung_acc data where the simulated data is currently generated. Ensure that the data is sampled at 800 Hz as specified.
-
Adjust Vehicle Speed:
- Set the
speed_kmh variable to your vehicle's actual speed in km/h. This is crucial for accurately converting time-domain data to spatial-domain (distance) data.
-
Run the Script:
- Execute the script in your Python environment. It will display the overall IRI, average IRI for each segment length, and plots illustrating the road profile and IRI distributions.
-
Interpret the Results:
- Lower IRI values indicate smoother roads, while higher values indicate rougher surfaces. Use the segment-wise IRI to identify specific road sections that may require maintenance.
Notes and Recommendations
-
Noise and Drift: Numerical integration of noisy acceleration data can lead to drift and inaccurate displacement estimates. Always filter your acceleration data appropriately before integration.
-
Variable Vehicle Speed: If the vehicle speed is not constant, you'll need to adjust the distance calculation accordingly. This script assumes a constant speed for simplicity.
-
Data Length: Ensure that your acceleration data covers enough distance to obtain meaningful IRI measurements, especially for larger segment lengths like 100 meters.
-
Validation: Compare the calculated IRI with known standards or reference measurements to validate the accuracy of the script.
Feel free to modify and enhance the script based on your specific requirements and data characteristics.