write a python script to calculate road profile and instant IRI, IRI 20m, and IRI 100 m, based on measured sprung and unsprung acceleration of a running car (sampling rate 800Hz). The car speed is varied from 30-80km. You should provide two methods using Kalman filter or using a quarter-car model.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Below is a Python script that calculates the road profile and computes the Instantaneous IRI (International Roughness Index), as well as IRI over 20 meters and 100 meters, based on measured sprung and unsprung accelerations of a running car. The script provides two methods:
Kalman Filter-Based Estimation: Uses a Kalman filter to estimate the road profile from acceleration data.
Quarter-Car Model-Based Estimation: Utilizes a quarter-car suspension model to derive the road profile.
Prerequisites
Before running the script, ensure you have the following Python packages installed:
numpy
scipy
matplotlib
You can install them using pip:
bash
pip install numpy scipy matplotlib
Script Overview
Data Simulation: For demonstration purposes, the script simulates sprung and unsprung acceleration data. In practice, you'd replace this with your actual measurements.
Kalman Filter Method: Estimates the road profile using a Kalman filter based on the acceleration data.
Quarter-Car Model Method: Estimates the road profile using a quarter-car suspension model.
IRI Calculation: Computes Instantaneous IRI, IRI over 20 meters, and IRI over 100 meters.
Visualization: Plots the estimated road profiles and IRI values.
Let's dive into the script.
python
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
# Constants
SAMPLE_RATE = 800 # Hz
DT = 1 / SAMPLE_RATE # Time step
VEHICLE_SPEED_KMH = np.linspace(30, 80, 500) # Varying speed from 30 to 80 km/h
VEHICLE_SPEED_MS = VEHICLE_SPEED_KMH * (1000 / 3600) # Convert to m/s
# Simulated acceleration data
# In practice, replace these with your actual measurements
def simulate_accelerations(time, road_profile, suspension_freq=1.0, damping=0.1):
"""
Simulate sprung and unsprung acceleration based on road profile.
"""
# Simple spring-damper model
sprung_acc = np.zeros_like(time)
unsprung_acc = np.zeros_like(time)
for i in range(1, len(time)):
sprung_acc[i] = suspension_freq**2 * (road_profile[i] - road_profile[i-1]) - damping * sprung_acc[i-1]
unsprung_acc[i] = road_profile[i]
return sprung_acc, unsprung_acc
# Generate a simple road profile for simulation
def generate_road_profile(length=5000, amplitude=0.05, wavelength=10):
"""
Generate a sinusoidal road profile for simulation.
"""
x = np.linspace(0, length, length * SAMPLE_RATE // VEHICLE_SPEED_MS.mean())
profile = amplitude * np.sin(2 * np.pi * x / wavelength)
return x, profile
# IRI Calculation
def calculate_iri(displacement, distance):
"""
Calculate IRI as the integral of suspension displacement over the given distance.
displacement: Suspension displacement in meters
distance: Distance in meters over which to calculate IRI
Returns IRI in m/m
"""
# IRI is typically scaled by 100 meters
iri = np.sum(np.abs(displacement)) / distance
return iri * 100 # Scale to meters per 100 meters
# Kalman Filter Based Road Profile Estimation
def kalman_filter_estimation(sprung_acc, unsprung_acc, dt):
"""
Estimate road profile using a Kalman filter based on acceleration data.
"""
# State Vector [road_position, road_velocity]
A = np.array([[1, dt],
[0, 1]])
B = np.array([[0.5 * dt**2],
[dt]])
H = np.array([[1, 0]]) # We measure road position directly
Q = np.eye(2) * 1e-5 # Process noise covariance
R = np.array([[1e-2]]) # Measurement noise covariance
n = len(sprung_acc)
x = np.zeros((2, n)) # State estimate
P = np.eye(2) # Estimate covariance
road_est = np.zeros(n)
for i in range(1, n):
# Predict
x_pred = A @ x[:, i-1] + B.flatten() * unsprung_acc[i]
P_pred = A @ P @ A.T + Q
# Measurement (assuming we can measure road position indirectly through acceleration)
z = sprung_acc[i] # This is a simplification
# Update
S = H @ P_pred @ H.T + R
K = P_pred @ H.T @ np.linalg.inv(S)
y = z - (H @ x_pred)
x[:, i] = x_pred + K.flatten() * y
P = (np.eye(2) - K @ H) @ P_pred
road_est[i] = x[0, i]
return road_est
# Quarter-Car Model Based Road Profile Estimation
def quarter_car_model_estimation(sprung_acc, unsprung_acc, dt):
"""
Estimate road profile using a quarter-car suspension model.
"""
# Suspension parameters (example values)
m_s = 250 # Sprung mass (kg)
m_u = 50 # Unsprung mass (kg)
k_s = 15000 # Suspension stiffness (N/m)
k_u = 170000 # Tire stiffness (N/m)
c_s = 1000 # Damping coefficient (Ns/m)
n = len(sprung_acc)
road_est = np.zeros(n)
# Initial conditions
z_s = 0
z_u = 0
z_s_dot = 0
z_u_dot = 0
for i in range(1, n):
# Calculate relative displacement and velocity
delta_z = z_s - z_u
delta_z_dot = z_s_dot - z_u_dot
# Equations of motion
z_s_ddot = (-k_s * delta_z - c_s * delta_z_dot + m_s * sprung_acc[i]) / m_s
z_u_ddot = (k_s * delta_z + c_s * delta_z_dot - k_u * z_u + m_u * unsprung_acc[i]) / m_u
# Integrate to get velocity and displacement
z_s_dot += z_s_ddot * dt
z_u_dot += z_u_ddot * dt
z_s += z_s_dot * dt
z_u += z_u_dot * dt
# Estimate road profile as tire displacement
road_est[i] = z_u
return road_est
# Main Function
def main():
# Simulate time and road profile
# For realistic speed variation, you would have time varying with speed
duration = 20 # seconds
time = np.linspace(0, duration, int(SAMPLE_RATE * duration))
# Generate a random road profile (in reality, this comes from measurements)
road_x, road_profile = generate_road_profile(length=duration * VEHICLE_SPEED_MS.mean(), amplitude=0.05, wavelength=10)
sprung_acc, unsprung_acc = simulate_accelerations(time, road_profile)
# Estimate road profile using Kalman Filter
road_est_kf = kalman_filter_estimation(sprung_acc, unsprung_acc, DT)
# Estimate road profile using Quarter-Car Model
road_est_qcm = quarter_car_model_estimation(sprung_acc, unsprung_acc, DT)
# Calculate IRI
# Assuming vehicle is moving forward, displacement can be converted to spatial domain
# IRI requires suspension displacement; here we take estimated road profile as proxy
# This is a simplification
iri_instant = np.abs(road_est_kf) # Instantaneous IRI
# For IRI over distances, we need to integrate over distance
# Convert displacement over time to displacement over distance
# I = sum |displacement_i| / total_distance
distance = VEHICLE_SPEED_MS.mean() * duration # Approximation
iri_20m = calculate_iri(road_est_kf, 20)
iri_100m = calculate_iri(road_est_kf, 100)
print(f"Instantaneous IRI (first 10 values): {iri_instant[:10]}")
print(f"IRI over 20 meters: {iri_20m:.4f} m/m")
print(f"IRI over 100 meters: {iri_100m:.4f} m/m")
# Plotting
plt.figure(figsize=(14, 8))
plt.subplot(3,1,1)
plt.plot(time, road_profile, label='Actual Road Profile')
plt.plot(time, road_est_kf, label='Estimated Road Profile (Kalman Filter)', alpha=0.7)
plt.plot(time, road_est_qcm, label='Estimated Road Profile (Quarter-Car Model)', alpha=0.7)
plt.xlabel('Time [s]')
plt.ylabel('Displacement [m]')
plt.legend()
plt.title('Road Profile Estimation')
plt.subplot(3,1,2)
plt.plot(time, iri_instant, label='Instantaneous IRI')
plt.xlabel('Time [s]')
plt.ylabel('IRI [m/m]')
plt.legend()
plt.title('Instantaneous IRI')
plt.subplot(3,1,3)
plt.bar(['20m IRI', '100m IRI'], [iri_20m, iri_100m], color=['blue', 'green'])
plt.ylabel('IRI [m/m]')
plt.title('IRI over 20m and 100m')
plt.tight_layout()
plt.show()
if __name__ == "__main__":
main()
Explanation
Data Simulation:
simulate_accelerations: Simulates sprung and unsprung accelerations based on a simple spring-damper model and a given road profile.
generate_road_profile: Generates a sinusoidal road profile for simulation purposes.
IRI Calculation:
calculate_iri: Calculates the IRI by integrating the absolute suspension displacement over a specified distance and scaling it to meters per 100 meters.
Kalman Filter Estimation:
kalman_filter_estimation: Implements a basic Kalman filter to estimate the road profile. The state vector includes road position and velocity. Note that in a real-world scenario, the measurement model would need to be more accurately defined based on available sensors and their relation to the road profile.
Quarter-Car Model Estimation:
quarter_car_model_estimation: Implements a quarter-car suspension model to estimate the road profile. The model computes the dynamics of the sprung and unsprung masses and estimates the road profile based on tire displacement.
Main Function:
Simulates a road profile and corresponding acceleration data.
Estimates the road profile using both the Kalman filter and the quarter-car model.
Calculates the Instantaneous IRI and IRI over 20 meters and 100 meters.
Plots the actual and estimated road profiles and IRI values.
Notes
Data Requirements: Replace the simulated road profile and acceleration data with your actual measurements for practical applications.
Model Parameters: The suspension parameters (m_s, m_u, k_s, k_u, c_s) in the quarter-car model are example values. You should calibrate them based on your vehicle's specifications.
IRI Calculation: The IRI calculation in this script is a simplification. For accurate IRI computation, especially over specific distances like 20m and 100m, you might need to implement sliding window integrations based on the actual speed and corresponding distance traveled.
Conclusion
This script provides a foundational approach to estimating the road profile and calculating the IRI using two different methods. Depending on your specific requirements and data quality, further refinements and calibrations might be necessary to achieve accurate and reliable results.