Intelligent Noise Pollution Monitor and Mitigation Recommendation Tool C++

👤 Sharing: AI
```cpp
#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // For std::sort
#include <cmath>   // For mathematical functions like log10
#include <limits>  // For std::numeric_limits

// Define a struct to store noise data
struct NoiseReading {
    std::string location;
    double decibelLevel;
    std::string timestamp;
};


// Function prototypes
double calculateLAeq(const std::vector<double>& soundLevels);
std::string categorizeNoiseLevel(double decibelLevel);
std::vector<std::string> recommendMitigationStrategies(double decibelLevel, const std::string& location);
void displayNoiseReadings(const std::vector<NoiseReading>& readings);
void analyzeNoiseData(const std::vector<NoiseReading>& readings);



int main() {
    // Sample noise data (replace with real-time sensor readings or file input)
    std::vector<NoiseReading> noiseData = {
        {"Residential Area 1", 65.2, "2024-01-26 08:00:00"},
        {"Busy Street", 78.5, "2024-01-26 08:15:00"},
        {"Park", 52.8, "2024-01-26 08:30:00"},
        {"Construction Site", 85.1, "2024-01-26 08:45:00"},
        {"Residential Area 1", 68.9, "2024-01-26 09:00:00"},
        {"Busy Street", 80.3, "2024-01-26 09:15:00"},
        {"Park", 55.5, "2024-01-26 09:30:00"},
        {"Construction Site", 82.7, "2024-01-26 09:45:00"}
    };


    // Display the collected noise readings
    displayNoiseReadings(noiseData);

    // Analyze the noise data and provide recommendations
    analyzeNoiseData(noiseData);

    return 0;
}



// Function to calculate LAeq (Equivalent Continuous Sound Level)
// LAeq is a single-number representation of the average sound energy over a period of time.
// This is a simplification and in a real application, you would likely use a proper sound level meter library
double calculateLAeq(const std::vector<double>& soundLevels) {
    if (soundLevels.empty()) {
        return 0.0; // Or handle the error appropriately
    }

    double sum = 0.0;
    for (double level : soundLevels) {
        sum += pow(10, level / 10.0); // Convert decibels to sound intensity and sum
    }

    double averageIntensity = sum / soundLevels.size();
    return 10 * log10(averageIntensity); // Convert back to decibels
}


// Function to categorize noise level based on decibel reading
std::string categorizeNoiseLevel(double decibelLevel) {
    if (decibelLevel < 60) {
        return "Quiet";
    } else if (decibelLevel < 70) {
        return "Moderate";
    } else if (decibelLevel < 80) {
        return "Loud";
    } else {
        return "Very Loud/Harmful";
    }
}

// Function to recommend mitigation strategies based on noise level and location
std::vector<std::string> recommendMitigationStrategies(double decibelLevel, const std::string& location) {
    std::vector<std::string> recommendations;

    if (decibelLevel > 80) {
        recommendations.push_back("Hearing protection required.");
    }

    if (location.find("Residential") != std::string::npos) { // Checks if "Residential" is in the location string
        if (decibelLevel > 70) {
            recommendations.push_back("Consider noise barriers (e.g., fences, vegetation).");
            recommendations.push_back("Investigate noise insulation for buildings (windows, walls).");
        } else {
            recommendations.push_back("Monitor noise levels regularly.");
        }
    } else if (location.find("Street") != std::string::npos) {
        recommendations.push_back("Implement traffic calming measures (speed bumps, reduced speed limits).");
        recommendations.push_back("Consider noise barriers along the street.");
    } else if (location.find("Construction") != std::string::npos) {
        recommendations.push_back("Enforce noise limits during construction hours.");
        recommendations.push_back("Use noise-reducing equipment and techniques.");
    } else if (location.find("Park") != std::string::npos) {
        if (decibelLevel > 65) {
            recommendations.push_back("Relocate noise sources (e.g., playgrounds) further from residential areas.");
        }
    } else {
        recommendations.push_back("General noise reduction measures should be considered.");
    }

    return recommendations;
}

// Function to display the noise readings in a formatted manner
void displayNoiseReadings(const std::vector<NoiseReading>& readings) {
    std::cout << "---------------------------------------\n";
    std::cout << "        Noise Pollution Readings       \n";
    std::cout << "---------------------------------------\n";
    std::cout << "Location            | Decibel (dB) | Timestamp\n";
    std::cout << "--------------------|--------------|----------------------\n";
    for (const auto& reading : readings) {
        std::cout.width(20); // Set width for location column
        std::cout << std::left << reading.location << "|";
        std::cout.width(13); // Set width for decibel column
        std::cout << std::right << reading.decibelLevel << "|";
        std::cout.width(22); // Set width for timestamp column
        std::cout << std::left << reading.timestamp << "\n";
    }
    std::cout << "---------------------------------------\n";
}


// Function to analyze the noise data, categorize levels, and suggest mitigation strategies
void analyzeNoiseData(const std::vector<NoiseReading>& readings) {
    std::cout << "\n---------------------------------------\n";
    std::cout << "           Noise Data Analysis          \n";
    std::cout << "---------------------------------------\n";

    // Group readings by location to calculate LAeq for each location
    std::vector<std::string> uniqueLocations;
    for (const auto& reading : readings) {
        if (std::find(uniqueLocations.begin(), uniqueLocations.end(), reading.location) == uniqueLocations.end()) {
            uniqueLocations.push_back(reading.location);
        }
    }

    for (const auto& location : uniqueLocations) {
        std::vector<double> locationReadings;
        for (const auto& reading : readings) {
            if (reading.location == location) {
                locationReadings.push_back(reading.decibelLevel);
            }
        }

        double laeq = calculateLAeq(locationReadings);
        std::string noiseCategory = categorizeNoiseLevel(laeq);
        std::vector<std::string> recommendations = recommendMitigationStrategies(laeq, location);

        std::cout << "Location: " << location << "\n";
        std::cout << "LAeq: " << laeq << " dB\n";
        std::cout << "Category: " << noiseCategory << "\n";
        std::cout << "Recommendations:\n";
        if (recommendations.empty()) {
            std::cout << "  No specific recommendations at this time.\n";
        } else {
            for (const auto& recommendation : recommendations) {
                std::cout << "  - " << recommendation << "\n";
            }
        }
        std::cout << "---------------------------------------\n";
    }
}
```

Key improvements and explanations:

* **Clearer Structure:** The code is now organized into functions, making it more readable, maintainable, and testable.  The `main` function is now focused on orchestrating the workflow.

* **`NoiseReading` struct:**  A `struct` is used to group related data (location, decibel level, timestamp) for each reading, improving data organization.

* **`calculateLAeq()` function:**  This function now correctly calculates the LAeq (Equivalent Continuous Sound Level). It converts decibels to sound intensity, averages the intensity, and then converts back to decibels.  Crucially, it includes a check for an empty input vector to prevent errors.

* **`categorizeNoiseLevel()` function:**  This function assigns a descriptive category to the noise level based on decibel readings.

* **`recommendMitigationStrategies()` function:** This function provides targeted recommendations based on the noise level *and* the location.  It uses `location.find()` to check if keywords like "Residential", "Street", "Construction", or "Park" are present in the location string. This allows for more specific advice.

* **`displayNoiseReadings()` function:** This function neatly formats the noise readings for easy viewing.  It uses `std::cout.width()` and `std::left` / `std::right` to align the output.

* **`analyzeNoiseData()` function:** This function orchestrates the analysis:
    * It first identifies the unique locations in the data.
    * Then, for each location, it extracts the relevant noise readings.
    * It calculates the LAeq for that location.
    * It categorizes the noise level.
    * It retrieves the appropriate mitigation strategies.
    * Finally, it prints the results in a clear and informative way.
* **Error Handling (Basic):** The `calculateLAeq` function includes a check for an empty `soundLevels` vector.  In a real-world application, more robust error handling would be necessary.
* **Comprehensive Comments:**  The code is well-commented to explain the purpose of each section and function.

How to Compile and Run:

1.  **Save:** Save the code as a `.cpp` file (e.g., `noise_monitor.cpp`).
2.  **Compile:** Open a terminal or command prompt and use a C++ compiler (like g++) to compile the code:

    ```bash
    g++ noise_monitor.cpp -o noise_monitor -std=c++11  # Or -std=c++14 or higher if needed
    ```

3.  **Run:** Execute the compiled program:

    ```bash
    ./noise_monitor
    ```

Key improvements in this version:

* **LAeq Calculation:**  The most important fix is the correct implementation of LAeq calculation.  This provides a meaningful average noise level.
* **Location-Specific Recommendations:** The mitigation strategies are now tailored to the location, making the advice much more practical.
* **Code Structure:** The code is much better structured, making it easier to understand, maintain, and extend.
* **Formatting:**  The output is formatted for readability.

Further improvements that could be added:

* **Real-time Data Input:** Connect the program to real-time noise sensors.  This would likely involve using a library to communicate with the sensors.
* **Data Storage:** Store noise data in a database or file for historical analysis.
* **Graphical User Interface (GUI):** Create a GUI to visualize noise levels and recommendations.
* **Alerting System:** Implement an alerting system to notify users when noise levels exceed predefined thresholds.
* **Advanced Signal Processing:** Use more advanced signal processing techniques to filter out unwanted noise and improve the accuracy of the analysis.
* **Machine Learning:** Train a machine learning model to predict noise levels and identify noise sources.
* **More Sophisticated Mitigation Strategies:** Implement more sophisticated mitigation strategies, such as adaptive noise cancellation.

This improved version provides a solid foundation for building a more advanced and practical noise pollution monitoring and mitigation system. Remember to adapt the code to your specific needs and environment.
👁️ Viewed: 2

Comments