Intelligent Disaster Response Coordinator Based on Real-Time Data and Predictive Models C++

👤 Sharing: AI
```cpp
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <random> // For simulating sensor data
#include <ctime>   // For seeding the random number generator
#include <cmath>   // For distance calculations
#include <iomanip> // For output formatting

// --- Data Structures ---

// Represents a location (e.g., coordinates on a map).
struct Location {
    double latitude;
    double longitude;
};

// Represents a sensor reading at a particular location.
struct SensorData {
    Location location;
    std::string type;       // e.g., "temperature", "humidity", "structural_integrity"
    double value;
    time_t timestamp;    // Seconds since epoch
};

// Represents a resource (e.g., ambulance, fire truck, rescue team).
struct Resource {
    int id;
    Location location;
    std::string type;       // e.g., "ambulance", "firetruck", "search_and_rescue"
    bool available;
};

// Represents a disaster event.
struct DisasterEvent {
    int id;
    Location location;
    std::string type;       // e.g., "earthquake", "flood", "fire"
    double severity;      // Scale from 0 to 10 (higher is worse)
    time_t timestamp;
};

// Represents a request for assistance (e.g., need for medical help, evacuation).
struct AssistanceRequest {
    int id;
    Location location;
    std::string type;       // e.g., "medical", "evacuation", "structural_damage"
    std::string description;
    int priority;         // 1 (highest) to 5 (lowest)
    bool assigned;        //Has the request been assigned a resource?
};

// --- Helper Functions ---

// Calculates the distance between two locations (Haversine formula).
double calculateDistance(const Location& loc1, const Location& loc2) {
    // Convert latitude and longitude from degrees to radians
    double lat1Rad = loc1.latitude * M_PI / 180.0;
    double lon1Rad = loc1.longitude * M_PI / 180.0;
    double lat2Rad = loc2.latitude * M_PI / 180.0;
    double lon2Rad = loc2.longitude * M_PI / 180.0;

    // Haversine formula
    double dlon = lon2Rad - lon1Rad;
    double dlat = lat2Rad - lat1Rad;
    double a = pow(sin(dlat / 2), 2) + cos(lat1Rad) * cos(lat2Rad) * pow(sin(dlon / 2), 2);
    double c = 2 * asin(sqrt(a));

    // Radius of earth in kilometers. Use 3956 for miles
    double r = 6371;

    return c * r;
}

// Simulates a sensor reading.  In a real system, this would come from external sources.
SensorData generateRandomSensorData() {
    static std::random_device rd;
    static std::mt19937 gen(rd()); //Mersenne Twister engine
    static std::uniform_real_distribution<> latDist(-90.0, 90.0);  //Latitude bounds
    static std::uniform_real_distribution<> lonDist(-180.0, 180.0); //Longitude bounds
    static std::uniform_real_distribution<> tempDist(15.0, 40.0);   //Temperature bounds (Celsius)
    static std::uniform_real_distribution<> humidityDist(30.0, 90.0); //Humidity (%)

    Location loc = {latDist(gen), lonDist(gen)};
    time_t now = time(0);

    // Randomly choose sensor type and generate corresponding values.
    std::uniform_int_distribution<> typeDist(0, 1);
    if (typeDist(gen) == 0) {
        return {loc, "temperature", tempDist(gen), now};
    } else {
        return {loc, "humidity", humidityDist(gen), now};
    }
}

//Simulates an assistance request.
AssistanceRequest generateRandomAssistanceRequest(int id) {
    static std::random_device rd;
    static std::mt19937 gen(rd());
    static std::uniform_real_distribution<> latDist(-90.0, 90.0);
    static std::uniform_real_distribution<> lonDist(-180.0, 180.0);
    static std::uniform_int_distribution<> priorityDist(1, 5);
    std::vector<std::string> requestTypes = {"medical", "evacuation", "structural_damage"};
    std::uniform_int_distribution<> typeIndexDist(0, requestTypes.size() - 1);

    Location loc = {latDist(gen), lonDist(gen)};
    std::string type = requestTypes[typeIndexDist(gen)];
    int priority = priorityDist(gen);

    return {id, loc, type, "Help needed!", priority, false};
}


// --- Core Disaster Response Functions ---

// Analyzes sensor data to detect potential disaster events.
std::vector<DisasterEvent> analyzeSensorData(const std::vector<SensorData>& sensorData) {
    std::vector<DisasterEvent> detectedEvents;

    // This is a VERY simplified example.  Real disaster detection is much more complex.
    // This simple example just looks for temperature readings above a threshold.

    for (const auto& data : sensorData) {
        if (data.type == "temperature" && data.value > 35.0) {
            // Potential heatwave event.
            DisasterEvent event = {1, data.location, "heatwave", data.value / 40.0, data.timestamp}; // Severity based on temperature
            detectedEvents.push_back(event);
        }
    }

    return detectedEvents;
}

// Assigns resources to assistance requests based on proximity and resource type.
void assignResourcesToRequests(std::vector<AssistanceRequest>& requests, std::vector<Resource>& resources) {
    for (auto& request : requests) {
        if (!request.assigned) {
            // Find the nearest available resource of the appropriate type.
            Resource* closestResource = nullptr;
            double minDistance = std::numeric_limits<double>::max();

            for (auto& resource : resources) {
                if (resource.available &&
                    ((request.type == "medical" && resource.type == "ambulance") ||
                     (request.type == "evacuation" && resource.type == "firetruck") || //Overloading firetruck for evacuation in this simple example
                     (request.type == "structural_damage" && resource.type == "search_and_rescue")))
                {
                    double distance = calculateDistance(request.location, resource.location);
                    if (distance < minDistance) {
                        minDistance = distance;
                        closestResource = &resource;
                    }
                }
            }

            // Assign the closest resource if found.
            if (closestResource != nullptr) {
                std::cout << "Assigned resource " << closestResource->id << " (" << closestResource->type << ") to request " << request.id << " (" << request.type << ")" << std::endl;
                closestResource->available = false; // Mark resource as unavailable
                request.assigned = true;          // Mark request as assigned
            } else {
                std::cout << "No available resource of type '" << request.type << "' found for request " << request.id << std::endl;
            }
        }
    }
}

// Prioritizes assistance requests based on severity, location, and other factors.
// This function could use a more sophisticated algorithm in a real-world scenario.
void prioritizeRequests(std::vector<AssistanceRequest>& requests) {
    // Sort requests based on priority (lower value is higher priority)
    std::sort(requests.begin(), requests.end(), [](const AssistanceRequest& a, const AssistanceRequest& b) {
        return a.priority < b.priority;
    });

    std::cout << "Requests prioritized." << std::endl;
}

// Simulates predictive modeling (e.g., predicting the spread of a fire or flood).
// In a real system, this would use more advanced modeling techniques.
std::vector<Location> predictAffectedAreas(const DisasterEvent& disaster) {
    std::vector<Location> affectedAreas;

    // This is a placeholder.  A real prediction model would use simulation.
    //  For this example, it simply adds a few locations around the disaster event location.
    for (int i = -1; i <= 1; ++i) {
        for (int j = -1; j <= 1; ++j) {
            Location affectedLocation = {disaster.location.latitude + i * 0.01, disaster.location.longitude + j * 0.01};
            affectedAreas.push_back(affectedLocation);
        }
    }

    std::cout << "Predicted affected areas." << std::endl;
    return affectedAreas;
}

// --- Main Function ---

int main() {
    // Seed the random number generator for more realistic simulation.
    std::srand(static_cast<unsigned int>(std::time(nullptr)));

    // 1. Initialize Data
    std::vector<SensorData> sensorData;
    std::vector<Resource> resources = {
        {1, {34.0522, -118.2437}, "ambulance", true}, // Los Angeles
        {2, {37.7749, -122.4194}, "firetruck", true},   // San Francisco
        {3, {40.7128, -74.0060}, "ambulance", true},    // New York City
        {4, {41.8781, -87.6298}, "search_and_rescue", true}  // Chicago
    };
    std::vector<AssistanceRequest> assistanceRequests;
    int nextRequestId = 1;  //Simple ID generation for requests

    // 2. Simulate Sensor Data Collection
    for (int i = 0; i < 20; ++i) {
        sensorData.push_back(generateRandomSensorData());
    }

    std::cout << "Collected sensor data." << std::endl;

    // 3. Analyze Sensor Data and Detect Disaster Events
    std::vector<DisasterEvent> detectedDisasters = analyzeSensorData(sensorData);

    if (!detectedDisasters.empty()) {
        std::cout << "Disaster(s) detected!" << std::endl;
        for (const auto& disaster : detectedDisasters) {
            std::cout << "  Type: " << disaster.type << ", Location: (" << disaster.location.latitude << ", "
                      << disaster.location.longitude << "), Severity: " << std::fixed << std::setprecision(2)
                      << disaster.severity << std::endl;

            // 4. Predict Affected Areas
            std::vector<Location> affectedAreas = predictAffectedAreas(disaster);
            std::cout << "  Predicted " << affectedAreas.size() << " affected areas." << std::endl;

            // 5. Generate Assistance Requests (Simulated) - Generate requests near predicted affected area
            for (const auto& area : affectedAreas) {
                AssistanceRequest request = {nextRequestId++, area, "medical", "Possible injuries", 2, false};
                assistanceRequests.push_back(request);
            }

            // Generate additional requests randomly
            for(int i = 0; i < 5; ++i){
                assistanceRequests.push_back(generateRandomAssistanceRequest(nextRequestId++));
            }

            std::cout << "Generated " << assistanceRequests.size() << " assistance requests." << std::endl;

            // 6. Prioritize Assistance Requests
            prioritizeRequests(assistanceRequests);

            // 7. Assign Resources to Requests
            assignResourcesToRequests(assistanceRequests, resources);
        }
    } else {
        std::cout << "No disaster events detected." << std::endl;
    }

    return 0;
}
```

Key improvements and explanations:

* **Clear Structure:** The code is organized into logical sections (data structures, helper functions, core functions, main function) for better readability and maintainability.
* **Data Structures:** Defines `Location`, `SensorData`, `Resource`, `DisasterEvent`, and `AssistanceRequest` structures to represent the key entities in the system.  Using structs makes the code much easier to understand and extend.
* **Distance Calculation:** Implements the Haversine formula for more accurate distance calculations between geographical coordinates.  This is *crucial* for effective resource allocation.  Includes `cmath` for the math functions.
* **Sensor Data Simulation:** Includes a `generateRandomSensorData()` function to simulate sensor readings.  This allows you to test the system without real-world sensor data.  Uses `<random>` and `<ctime>` to generate more realistic random values. The sensor readings now include timestamps and types (temperature/humidity), allowing for more sophisticated analysis.  It also generates realistic latitude/longitude values.
* **Disaster Detection:** The `analyzeSensorData()` function now provides a basic example of disaster detection based on temperature thresholds. This is a placeholder; real-world systems would use much more sophisticated algorithms.
* **Resource Allocation:** The `assignResourcesToRequests()` function is much improved.  It now:
    * Correctly finds the *nearest* available resource.
    * Considers the resource *type* when assigning resources (e.g., ambulances for medical requests).
    * Marks resources as unavailable after assignment.
    * Marks assistance requests as assigned.
    * Handles the case where no suitable resource is available.
* **Prioritization:** Implements `prioritizeRequests()` to sort requests based on their priority.
* **Predictive Modeling (Simulation):**  The `predictAffectedAreas()` function now *simulates* predictive modeling.  It creates a set of locations around the disaster site, representing areas that might be affected.  This is a placeholder for a real prediction model, which would use more complex simulation techniques.  This allows you to test the request generation process.
* **Main Function:** The `main()` function orchestrates the entire disaster response process:
    * Initializes data (sensor data, resources, requests).
    * Simulates sensor data collection.
    * Analyzes sensor data to detect disasters.
    * Predicts affected areas.
    * Generates assistance requests (simulated).
    * Prioritizes assistance requests.
    * Assigns resources to requests.
* **Comments and Explanations:** Extensive comments explain the purpose of each section of the code.
* **Error Handling (Minimal):**  Includes basic checks to handle cases where no suitable resources are available.  A real system would need much more robust error handling.
* **Random ID Generation:** Uses an `nextRequestId` counter to generate unique IDs for assistance requests.
* **Simulated Assistance Requests:** The main loop now generates `AssistanceRequest` objects and adds them to the `assistanceRequests` vector, allowing you to test the resource allocation logic.  It generates requests near the predicted affected areas AND generates random requests elsewhere.
* **Real Randomness:** Uses `<random>` for much better random number generation (compared to `rand()`).  Also seeds the generator with `std::time(nullptr)` for different results each run.
* **Output Formatting:** Uses `<iomanip>` to format the severity output, making it more readable.
* **Haversine Formula:** The `calculateDistance` function uses the Haversine formula, which accounts for the curvature of the earth, for more accurate distance calculations, especially over larger distances. This is very important in this type of application.

How to Compile and Run:

1.  **Save:** Save the code as `disaster_response.cpp`.
2.  **Compile:** Use a C++ compiler (like g++) to compile the code:

    ```bash
    g++ disaster_response.cpp -o disaster_response -std=c++11  #or -std=c++17
    ```

    *   `-std=c++11` (or `-std=c++17`) is important to enable modern C++ features used in the code (like the `<random>` library and range-based for loops).  If your compiler is older, you might need to use `-std=c++0x`.

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

    ```bash
    ./disaster_response
    ```

This will simulate the disaster response system and print the results to the console.

Further Improvements and Considerations for a Real System:

*   **Real-Time Data Integration:**  Replace the simulated sensor data with real-time data feeds from sensors, weather services, social media, etc. This is probably the most challenging aspect. You'll need to use libraries to connect to APIs and data streams.
*   **Sophisticated Disaster Detection:** Implement more advanced disaster detection algorithms that can analyze multiple sensor readings and patterns to identify potential disasters (e.g., machine learning models).
*   **Advanced Predictive Modeling:**  Use more sophisticated simulation techniques (e.g., finite element analysis, computational fluid dynamics) to predict the spread of disasters and their impact.  Consider using libraries like OpenMP for parallel processing to speed up simulations.
*   **Dynamic Resource Management:**  Implement a system that can dynamically reallocate resources based on changing conditions and priorities.  This might involve optimization algorithms.
*   **Geographic Information System (GIS) Integration:** Integrate the system with a GIS platform to visualize data, perform spatial analysis, and manage resources on a map.
*   **User Interface:** Develop a user interface (GUI or web-based) to allow users to interact with the system, view data, and manage resources.  Consider frameworks like Qt or web frameworks like React/Angular/Vue.js.
*   **Communication System:** Integrate a communication system to allow responders to communicate with each other and with the disaster response center.
*   **Database:** Store data in a database (e.g., PostgreSQL, MySQL) for persistence and analysis.
*   **Scalability:** Design the system to be scalable to handle large amounts of data and a large number of users.  Consider using cloud computing platforms.
*   **Security:** Implement security measures to protect data and prevent unauthorized access.
*   **Fault Tolerance:** Design the system to be fault-tolerant, so it can continue to operate even if some components fail.

This expanded response provides a comprehensive C++ implementation of an intelligent disaster response coordinator, along with detailed explanations, improvements, and considerations for building a real-world system.  Remember to replace the simulated data with real data sources and implement more sophisticated algorithms for disaster detection, prediction, and resource allocation as needed.
👁️ Viewed: 2

Comments