Real-time wildfire risk assessment system combining environmental data, fire behavior modeling, and Prolog-based reasoning.
🌐 Live Demo: https://fireguard-xo33.onrender.com/
Wildfires continue to pose significant threats globally. FireGuard was developed to provide real-time wildfire risk assessment by combining environmental data, fire behavior modeling, and a Prolog-based reasoning system. The goal is to empower first responders, emergency planners, and the public with actionable insights for evacuation, resource allocation, and fire management.
FireGuard integrates multiple layers to assess wildfire risk:
- Weather Data: Temperature, humidity, wind speed, and precipitation are fetched in real-time from the Open-Meteo API.
- Rain History: Historical rainfall is analyzed to estimate days since last rain and its effect on fuel moisture.
- Topography: Elevation and slope are estimated using the Open-Elevation API to classify terrain.
- Population & Infrastructure: Population density and critical infrastructure are inferred from OpenStreetMap APIs.
FireGuard uses classical fire science models:
- Rothermel Equation: Predicts fire spread rate.
- Byram Equation: Calculates fireline intensity.
- Flame Length & Height: Derived from fire intensity.
- Safety Zones, Burn Area, Escape Time: Calculated using fire behavior metrics.
Risk is evaluated across multiple parameters:
| Factor | Scoring | Notes |
|---|---|---|
| Fuel Moisture | 0–30 | Very critical |
| Temperature | 0–20 | Higher temp = higher risk |
| Humidity | 0–20 | Lower humidity = higher risk |
| Wind Speed | 0–20 | Stronger wind = higher risk |
| Topography | 0–15 | Steeper slopes = faster spread |
| Population Density | 0–10 | More people at risk |
| Infrastructure | 0–15 | Critical infrastructure increases consequence |
Total score is mapped to risk levels: Very Low, Low, Medium, High, Very High, Extreme.
Evacuation and resource recommendations are provided based on risk level.
- FDI is computed dynamically using temperature, humidity, wind, and rainfall history.
- FDI numeric value is mapped to categories: Blue, Green, Yellow, Orange, Red.
- Dynamic Prolog Facts: Each area is dynamically added/updated in the Prolog knowledge base.
- Classification: Prolog evaluates all parameters to assign fire risk, evacuation recommendations, and required resources.
- JSON Output: Results can be easily integrated with Python for further processing or visualization.
Users can query the following fire science calculations via an integrated Prolog chatbot interface:
- Fireline Intensity: Calculate fire intensity based on fuel and environmental parameters
- Flame Length: Estimate flame height from intensity calculations
- Safety Zones: Compute safe evacuation distances from the fire
- Burn Area: Project area affected by fire spread over time
- Escape Time: Calculate time required to safely evacuate
- Risk Level: Get dynamic risk assessment for arbitrary parameter combinations
- Python scripts fetch real-time environmental data.
- Fire science equations are implemented in Prolog for deterministic reasoning.
- Random Forest machine learning model (legacy) complements the system with historical predictions.
- Python-Prolog integration allows dynamic area creation and real-time classification.
- Flask web application provides an intuitive web interface for easy access.
- Results include risk levels, evacuation recommendations, and resource allocation.
- Fetching and integrating multiple external APIs reliably.
- Converting continuous environmental data into categorical scores for Prolog classification.
- Maintaining real-time performance while running complex calculations and external queries.
- Handling dynamic Prolog facts for multiple areas without conflicts.
- Fully dynamic, real-time fire risk system combining Python, Prolog, and machine learning.
- Provides actionable outputs for firefighters and emergency responders.
- Interactive web interface with clean, modern UI for easy access.
- Prolog chatbot interface for advanced queries.
- Programmatic JSON outputs for integration with other systems.
- Supports multi-area comparisons with priority ordering.
- Integrate live satellite and drone feeds to improve fire detection.
- Expand to more granular local sensor data for vegetation and soil moisture.
- Improve predictive accuracy with additional datasets.
- Add real-time map visualization for multiple locations.
- Implement user authentication and saved location history.
FireGuard is deployed as a unified Flask application on Render with Docker:
- Production URL: https://prolog-api.onrender.com
- API Endpoints:
GET /- Web interfaceGET /api/health- Generic health checkPOST /api/analyze- Fire risk analysis for coordinatesPOST /api/prolog/classify- Direct Prolog classification with parametersGET /api/prolog/health- Prolog service health checkPOST /api/chatbot- Interactive chatbot queries
- Frontend: Served from
templates/andstatic/by Flask - Backend: Merged Flask app combining fire analysis and Prolog reasoning
- Container: Docker image with Python 3.13 + SWI-Prolog
- WSGI Server: Gunicorn (production-ready)
PORT- Server port (default: 5000)MOCK_WEATHER- Set to1to use mock weather data (for testing/rate limit avoidance)
- Python 3.8 or higher
- SWI-Prolog installed and accessible via
swiplcommand - Virtual environment (recommended)
- Clone the repository:
git clone <repository_url>
cd <repository_directory>- Create and activate a virtual environment (recommended):
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate- Install required Python libraries:
pip install -r requirements.txt- Ensure SWI-Prolog is installed:
swipl --versionIf not installed:
- macOS:
brew install swi-prolog - Linux:
sudo apt-get install swi-prolog - Windows: Download from SWI-Prolog website
- Activate the virtual environment (if not already active):
source .venv/bin/activate- Start the Flask server:
python app.pyOr use the convenience script:
./run.sh- Open your browser and navigate to:
http://localhost:5000
- Enter coordinates (latitude and longitude) and click "Analyze Fire Risk"
The web interface provides a user-friendly way to analyze fire risk with real-time data visualization.
For programmatic access, you can run the Python analysis directly:
python fdi.pyThis will analyze predefined locations and print results to the console.
-
Open SWI-Prolog or an s(CASP) interpreter.
-
Load
prolog.pland run:
chatbot.
priority_list(OrderedResults).- Query fireline intensity, flame length, safety zones, burn area, escape time, or risk level interactively.
- Start the Flask server:
python app.py - Open
http://localhost:5000in your browser - Enter coordinates:
- Frisco, TX: Latitude: 33.1507, Longitude: -96.8236
- Los Angeles, CA: Latitude: 34.0522, Longitude: -118.2437
- San Francisco, CA: Latitude: 37.7749, Longitude: -122.4194
- Click "Analyze Fire Risk" to view results
Python script dynamically analyzes multiple locations:
from fdi import analyze_location_dynamic
locations = [
(33.1507, -96.8236, "frisco_tx"),
(34.0522, -118.2437, "los_angeles_ca"),
(37.7749, -122.4194, "san_francisco_ca"),
]
for lat, lon, name in locations:
result = analyze_location_dynamic(lat, lon, area_name=name)
print(f"{name}: {result['prolog_classification'].get('RiskLevel', 'Unknown')} risk")Each location outputs risk classification, evacuation status, resources needed, and FDI category.
Production API (deployed on Render):
# Health check
curl https://prolog-api.onrender.com/api/health
# Analyze fire risk for coordinates
curl -X POST https://prolog-api.onrender.com/api/analyze \
-H "Content-Type: application/json" \
-d '{"latitude": 33.1507, "longitude": -96.8236, "area_name": "frisco_tx"}'
# Direct Prolog classification
curl -X POST https://prolog-api.onrender.com/api/prolog/classify \
-H "Content-Type: application/json" \
-d '{
"area_name": "test_area",
"fuel": "moderate",
"temp": "moderate",
"hum": "moderate",
"wind": "moderate",
"topo": "flat",
"pop": "low",
"infra": "no_critical"
}'Local API:
curl -X POST http://localhost:5000/api/analyze \
-H "Content-Type: application/json" \
-d '{"latitude": 33.1507, "longitude": -96.8236, "area_name": "frisco_tx"}'The chatbot API allows you to calculate fire science metrics programmatically:
# Calculate fireline intensity
curl -X POST http://localhost:5000/api/chatbot \
-H "Content-Type: application/json" \
-d '{
"query_type": "fireline_intensity",
"params": {
"I": 100,
"P": 50,
"W": 20,
"S": 30,
"B": 5,
"E": 10,
"H": 15,
"H_Yield": 8000,
"A_Fuel": 300
}
}'
# Calculate flame length
curl -X POST http://localhost:5000/api/chatbot \
-H "Content-Type: application/json" \
-d '{
"query_type": "flame_length",
"params": {"I": 500}
}'
# Calculate safety zone distance
curl -X POST http://localhost:5000/api/chatbot \
-H "Content-Type: application/json" \
-d '{
"query_type": "safety_zone",
"params": {"C": 0.5, "I": 1000, "N": 0.5}
}'
# Get risk level for custom parameters
curl -X POST http://localhost:5000/api/chatbot \
-H "Content-Type: application/json" \
-d '{
"query_type": "risk_level",
"params": {
"fuel": "heavy",
"temp": "high",
"hum": "low",
"wind": "high",
"topo": "steep",
"pop": "high",
"infra": "yes"
}
}'To avoid Open-Meteo API rate limits during development:
# Local testing
MOCK_WEATHER=1 python app.py
# Or test analysis directly
MOCK_WEATHER=1 python -c "
from fdi import analyze_location_dynamic
import json
result = analyze_location_dynamic(33.1507, -96.8236, 'test')
print(json.dumps(result, indent=2))
"FireGuard/
├── app.py # Merged Flask application (web + API)
├── fdi.py # Fire risk analysis logic with MOCK_WEATHER support
├── prolog.pl # Prolog knowledge base (dynamic facts enabled)
├── Dockerfile # Docker build for Render deployment
├── requirements.txt # Python dependencies (includes gunicorn)
├── build.sh # Build script (no-op when using Docker)
├── templates/
│ └── index.html # Web interface template
├── static/
│ ├── css/
│ │ └── style.css # Styling with red fire theme
│ └── js/
│ └── main.js # Frontend JavaScript
├── api/
│ └── prolog/ # Vercel serverless functions (optional)
│ ├── classify.js
│ └── health.js
├── apitests.py # API testing utilities
└── README.md # This file
- ✅ Web Interface: Modern, responsive web UI with red fire-themed design
- ✅ Real-time Analysis: Fetches live weather and environmental data via Open-Meteo API
- ✅ Multiple Interfaces: Web UI, REST API, command-line script, and interactive Prolog chatbot
- ✅ Production Deployment: Dockerized on Render with Gunicorn
- ✅ Mock Weather Mode: Test without API rate limits
- ✅ Dynamic Prolog Facts: Runtime assertion of area data for multi-area analysis
- ✅ Comprehensive Results: Weather, topography, FDI, risk classification, and recommendations
- ✅ Dark Mode Toggle: Automatic theme detection and manual toggle with localStorage persistence
- ✅ Geolocation Support: One-click location detection using browser Geolocation API
- ✅ Quick Presets: Pre-configured wildfire zones (California, Oregon, Colorado, Arizona, Texas)
- ✅ Interactive Chatbot: Calculate fireline intensity, flame length, safety zones, burn area, escape time, and risk levels
- ✅ Fire Behavior Modeling: Rothermel equation for spread rate, Byram equation for intensity
- ✅ Risk Scoring System: Multi-factor analysis including fuel moisture, temperature, humidity, wind, topography, population, and infrastructure
- ✅ Risk Explanation: Detailed "Why This Risk?" breakdown showing critical factors and contributing analysis
- ✅ Fire Danger Index (FDI): Dynamic FDI calculation with categorical mapping (Blue→Green→Yellow→Orange→Red)
- ✅ Environmental Data Integration:
- Weather data from Open-Meteo
- Topography from Open-Elevation API
- Population density from OpenStreetMap
- 90-day rainfall history analysis
- ✅ JSON API Output: Structured, parseable results for integration with external systems
- ✅ Connection Pooling: Optimized API calls with session reuse and retry logic
- ✅ Error Handling: Graceful degradation with fallback values on API failures
- ✅ Input Validation: Parameter validation with clear error messages
- ⚡ 2-3x Faster API Calls: Connection pooling with global session reuse (~80MB → 2MB overhead)
- ⚡ 15% FDI Speedup: Pre-computed lookup table constants
- ⚡ 50% Faster Prolog Updates: Line-based string matching vs complex regex
- ⚡ 3-4x Parallel Testing: Concurrent test execution with ThreadPoolExecutor
- ⚡ Smart Caching: Archive API (no expiration), Forecast API (1-hour expiration)
- ⚡ Subprocess Optimization: Explicit timeout parameters, better error handling
- Backend: Python 3.13, Flask, Gunicorn
- Logic Engine: SWI-Prolog
- APIs: Open-Meteo (weather), Open-Elevation (topography), OpenStreetMap (population/infrastructure)
- Deployment: Docker, Render
- Frontend: HTML, CSS, JavaScript