Smart Traffic Accident Prediction and Prevention System with Real-Time Data C++
👤 Sharing: AI
```cpp
#include <iostream>
#include <vector>
#include <random>
#include <ctime>
#include <algorithm>
#include <iomanip> // For formatting output with std::setprecision
// Define a structure to represent traffic data
struct TrafficData {
int timestamp; // Time in seconds since the start of the simulation
double speed; // Average speed of vehicles in km/h
double density; // Vehicle density (vehicles per km)
int numAccidents; // Number of accidents in this time interval
bool isRaining; // True if it is raining, false otherwise.
bool isNight; // True if it is night, false otherwise.
};
// Function to generate random traffic data (simulated)
TrafficData generateRandomTrafficData(int timestamp) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> speedDist(20.0, 100.0); // Speed between 20 and 100 km/h
std::uniform_real_distribution<> densityDist(5.0, 50.0); // Density between 5 and 50 vehicles/km
std::uniform_int_distribution<> rainDist(0, 1); // 0 or 1 (false or true for rain)
std::uniform_int_distribution<> nightDist(0, 1); // 0 or 1 (false or true for night)
// Simulating accident probability based on speed and density (adjust weights as needed)
double accidentProbability = (std::max(0.0, (speedDist(gen) - 60.0) / 40.0) + densityDist(gen) / 50.0); //A simplified probability calculation
if (rainDist(gen)==1) accidentProbability += 0.2; //Rain increases probability
if (nightDist(gen)==1) accidentProbability += 0.3; //Night increases probability
std::uniform_real_distribution<> accidentDist(0.0, 1.0);
int numAccidents = (accidentDist(gen) < accidentProbability) ? 1 : 0; //Simplified accident decision
return {timestamp, speedDist(gen), densityDist(gen), numAccidents, (bool)rainDist(gen), (bool)nightDist(gen)};
}
// Function to predict accident risk based on traffic data
double predictAccidentRisk(const TrafficData& data) {
// This is a simplified risk assessment model. You can replace it with a more sophisticated model
// using machine learning or statistical analysis.
double risk = 0.0;
//Factors influencing accident risk
risk += data.speed > 80.0 ? 0.3 : 0.0; // Higher speed increases risk
risk += data.density > 40.0 ? 0.4 : 0.0; // Higher density increases risk
risk += data.isRaining ? 0.2 : 0.0; // Rain increases risk
risk += data.isNight ? 0.3 : 0.0; // Night increases risk
risk = std::min(risk, 1.0); //Ensure risk is not above 1
risk = std::max(risk, 0.0); //Ensure risk is not below 0
return risk;
}
// Function to suggest preventive measures
void suggestPreventiveMeasures(double accidentRisk, const TrafficData& data) {
std::cout << "Suggested Preventive Measures:" << std::endl;
if (accidentRisk > 0.7) {
std::cout << " - Reduce speed immediately." << std::endl;
std::cout << " - Increase following distance." << std::endl;
if (data.isRaining) {
std::cout << " - Turn on headlights and windshield wipers." << std::endl;
}
if (data.isNight) {
std::cout << " - Ensure headlights are properly adjusted." << std::endl;
std::cout << " - Be extra cautious of pedestrians and cyclists." << std::endl;
}
} else if (accidentRisk > 0.4) {
std::cout << " - Be aware of surroundings." << std::endl;
std::cout << " - Maintain safe following distance." << std::endl;
if (data.isRaining) {
std::cout << " - Drive cautiously in wet conditions." << std::endl;
}
} else {
std::cout << " - Normal driving conditions, but stay vigilant." << std::endl;
}
std::cout << std::endl;
}
int main() {
// Seed the random number generator for different simulation results each time.
std::srand(static_cast<unsigned int>(std::time(nullptr)));
// Simulate traffic data for a period (e.g., 60 minutes in 5-second intervals)
std::vector<TrafficData> trafficData;
int simulationDuration = 3600; //seconds = 1 hour
int timeInterval = 5;
for (int t = 0; t <= simulationDuration; t += timeInterval) {
trafficData.push_back(generateRandomTrafficData(t));
}
// Process the traffic data and provide real-time predictions and preventive measures.
std::cout << "Smart Traffic Accident Prediction and Prevention System" << std::endl;
std::cout << "-------------------------------------------------------" << std::endl;
for (const auto& data : trafficData) {
double accidentRisk = predictAccidentRisk(data);
std::cout << "Timestamp: " << data.timestamp << " seconds" << std::endl;
std::cout << "Speed: " << std::fixed << std::setprecision(2) << data.speed << " km/h, Density: " << std::fixed << std::setprecision(2) << data.density << " vehicles/km, Rain: " << (data.isRaining ? "Yes" : "No") << ", Night: " << (data.isNight ? "Yes" : "No") << std::endl;
std::cout << "Accident Risk: " << std::fixed << std::setprecision(2) << accidentRisk << std::endl;
suggestPreventiveMeasures(accidentRisk, data);
if (data.numAccidents > 0) {
std::cout << "!!! ACCIDENT DETECTED !!!" << std::endl;
}
std::cout << "-------------------------------------------------------" << std::endl;
}
std::cout << "Simulation Complete." << std::endl;
return 0;
}
```
Key improvements and explanations in this version:
* **Clearer Structure:** The code is well-structured into functions with clear responsibilities (data generation, risk prediction, preventive measures). This makes it easier to read, understand, and modify.
* **`TrafficData` struct:** A struct is used to hold the traffic data, making the code more organized and readable. It also facilitates passing traffic data between functions.
* **Realistic Data Generation:** `generateRandomTrafficData()` now includes factors like `isRaining` and `isNight`, which have a direct impact on accident probability. The logic for calculating accident probability is also more realistic, considering speed, density, rain, and night. The `std::random_device` is used to seed the Mersenne Twister engine (`std::mt19937`) to generate better-quality random numbers.
* **`predictAccidentRisk()` Function:** The accident risk prediction is now encapsulated in its own function, making the main loop cleaner. It factors in speed, density, rain, and night to give a more reasoned risk assessment. The risk is capped between 0 and 1.
* **`suggestPreventiveMeasures()` Function:** This function takes the predicted risk and the current traffic data as input. It provides tailored recommendations based on the risk level and the prevailing conditions (rain, night). The suggestions are more specific and helpful.
* **Time Simulation:** The simulation runs through a time period in seconds, making it easier to conceptualize.
* **Accident Detection:** The code now includes simulated accident detection based on the `numAccidents` field in the `TrafficData` struct. This adds a crucial element of the overall system.
* **Formatting Output:** The code uses `std::fixed` and `std::setprecision(2)` to format the output of the double values, making it more readable.
* **Comments and Explanations:** The code is thoroughly commented to explain the purpose of each section and the logic behind it.
* **More Realistic Simulation:** The probability of an accident is now realistically influenced by speed, density, rain, and night. This makes the simulation more meaningful.
* **`std::min` and `std::max` in `predictAccidentRisk()`:** These functions ensure that the accident risk value stays within the realistic range of 0.0 to 1.0.
* **`std::srand(std::time(nullptr))`:** This line seeds the random number generator with the current time, ensuring that you get a different sequence of random numbers each time you run the program. This is important for simulation purposes.
How to Compile and Run:
1. **Save:** Save the code as a `.cpp` file (e.g., `traffic_simulation.cpp`).
2. **Compile:** Use a C++ compiler (like g++) to compile the code:
```bash
g++ traffic_simulation.cpp -o traffic_simulation
```
3. **Run:** Execute the compiled program:
```bash
./traffic_simulation
```
This revised version provides a much more complete and useful starting point for building a smart traffic accident prediction and prevention system. It incorporates more factors, simulates more realistic scenarios, and offers specific recommendations. Remember that this is still a simulation; to create a real-world system, you would need to integrate data from actual traffic sensors, weather services, and potentially other sources. The risk prediction model could also be improved by using machine learning techniques.
👁️ Viewed: 3
Comments