Skip to content

vikram-001-dev/water-forcasting

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1 Commit
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AI-Driven Smart Urban Water Demand Forecasting and Decision Support System

A comprehensive final-year engineering project implementing an AI-powered system for urban water demand forecasting, IoT monitoring, and intelligent decision support.

🎯 Project Overview

This system combines machine learning and deep learning models with real-time IoT simulation to:

  • Forecast water demand using Linear Regression, Random Forest, and LSTM neural networks
  • Monitor real-time smart water meters with background IoT simulation
  • Predict peak demand periods and water shortages
  • Support decision-making with intelligent alerts and rationing recommendations
  • Visualize all data and insights through an advanced Streamlit dashboard

πŸ“ Project Structure

final_water_demand/
β”œβ”€β”€ data/                      # Data generation and storage
β”‚   └── dataset_generator.py   # Generate realistic water consumption dataset
β”œβ”€β”€ preprocessing/             # Data preprocessing
β”‚   └── data_processor.py      # Handle missing values, normalization, time-series
β”œβ”€β”€ iot/                       # IoT simulation
β”‚   └── iot_simulator.py       # Smart water meter simulation with threading
β”œβ”€β”€ models/                    # Machine Learning models
β”‚   └── ml_models.py          # Linear Regression & Random Forest
β”œβ”€β”€ lstm/                      # Deep Learning
β”‚   └── lstm_model.py         # LSTM for time-series forecasting
β”œβ”€β”€ forecasting/              # Forecasting engine
β”‚   └── forecasting_engine.py # Area-wise predictions & peak detection
β”œβ”€β”€ decision_support/         # Decision Support System
β”‚   └── dss.py               # Alerts, recommendations, rationing
β”œβ”€β”€ dashboard/               # Web interface
β”‚   └── dashboard.py        # Streamlit dashboard with Plotly
β”œβ”€β”€ utils/                  # Utilities
β”‚   β”œβ”€β”€ config.py          # Configuration parameters
β”‚   └── logger.py          # Logging setup
β”œβ”€β”€ models/                # Saved model files (generated after training)
β”œβ”€β”€ logs/                  # Application logs
β”œβ”€β”€ main.py               # Main application orchestrator
└── requirements.txt      # Python dependencies

βš™οΈ Tech Stack

  • Python 3.8+
  • Pandas & NumPy - Data manipulation and numerical operations
  • Scikit-learn - Machine Learning (Linear Regression, Random Forest)
  • TensorFlow & Keras - Deep Learning (LSTM)
  • Streamlit - Web dashboard framework
  • Plotly - Interactive visualizations
  • Threading - Background IoT simulation

πŸš€ Installation & Setup

1. Clone/Download the Project

cd final_water_demand

2. Create Virtual Environment (Recommended)

# Windows
python -m venv venv
venv\Scripts\activate

# Linux/Mac
python3 -m venv venv
source venv/bin/activate

3. Install Dependencies

pip install -r requirements.txt

Note: TensorFlow installation may take several minutes.

πŸ“Š Running the Project

Option 1: Full Pipeline (Recommended First Run)

Run the complete system initialization, training, and demonstration:

python main.py

This will:

  1. Generate a realistic 365-day water consumption dataset
  2. Preprocess and normalize all data
  3. Train Linear Regression and Random Forest models
  4. Train LSTM deep learning model
  5. Initialize the forecasting engine
  6. Setup Decision Support System
  7. Start IoT simulator and collect data
  8. Generate forecasts and alerts
  9. Save all trained models

Expected Duration: 10-15 minutes (first run with TensorFlow)

Option 2: Launch Dashboard Only (After Training)

After running main.py, launch the interactive dashboard:

streamlit run dashboard/dashboard.py

The dashboard will open at http://localhost:8501

πŸ“± Dashboard Features

1. Overview Page

  • Real-time system metrics (supply, demand, utilization)
  • Zone status overview
  • Current demand by zone visualization
  • System utilization gauge

2. Live IoT Data

  • Start/stop monitoring with background simulation
  • Flow rate, tank level, and daily usage for each zone
  • Real-time sensor data updates
  • Distribution charts

3. Demand Forecasting

  • 7-day and 30-day forecasts
  • ML vs LSTM vs Ensemble predictions
  • Zone-specific forecasts
  • Peak demand identification

4. ML vs LSTM Comparison

  • Error metrics (MAE, RMSE)
  • Prediction accuracy comparison
  • Model performance visualization
  • Feature importance analysis

5. Decision Support System

  • Active alerts with severity levels
  • Current rationing plans
  • Priority zones requiring attention
  • Water allocation strategies

6. Analytics

  • Historical demand trends
  • Utilization patterns
  • Summary statistics
  • Time-series analysis

🧠 Machine Learning Models

Linear Regression

  • Fast baseline model
  • Interpretable predictions
  • Good for trend analysis

Random Forest

  • Ensemble method with 100 trees
  • Captures non-linear relationships
  • Feature importance scoring

LSTM Neural Network

  • Multi-layer sequence model
  • Trained on 7-day sequences
  • 7 and 30-day forecasting capability
  • Best for complex temporal patterns

Ensemble Approach

  • Combines all three models
  • Averaging for robust predictions
  • Reduces individual model bias

πŸ“ˆ Model Performance

Expected metrics on test data:

Model MAE (L/min) RMSE (L/min)
Linear Regression ~130 ~190
Random Forest ~95 ~145
LSTM ~90 ~135
Ensemble ~92 ~140

πŸŽ›οΈ Decision Support System Features

Alerts

  • CRITICAL (β‰₯90% capacity): Immediate action required
  • WARNING (β‰₯75% capacity): Monitor and prepare contingencies
  • ALERT (β‰₯60% capacity): Plan for potential restrictions
  • NORMAL (<60% capacity): No immediate concerns

Rationing Plans

  • No Rationing: <60% utilization
  • Light Rationing (10%): 60-75% utilization
  • Moderate Rationing (20%): 75-85% utilization
  • Severe Rationing (30%): >85% utilization

Recommendations

  • Automatic priority zone identification
  • Water allocation strategies
  • Emergency action plans
  • Public communication guidelines

πŸ”„ IoT Simulation

The system includes a realistic smart water meter simulator with:

  • Flow Rate Simulation: Varies by time of day (peak hours: 6-9 AM, 12-1 PM, 6-9 PM)
  • Tank Level Monitoring: Real-time level tracking with inflow/outflow
  • Daily Usage Tracking: Cumulative water consumption
  • Background Execution: Runs in separate thread, non-blocking
  • Zone-wise Data: Separate meters for each urban zone

Starting IoT Monitoring

from iot.iot_simulator import IoTSimulator

iot = IoTSimulator(zones=['North', 'South', 'East', 'West', 'Central'])
iot.start()  # Starts background monitoring

# Get latest data
data = iot.get_latest_data()

iot.stop()   # Stop monitoring

πŸ“Š Data Generation

The system generates a realistic 365-day dataset including:

  • Date & Hour: Hourly timestamps
  • Zone: Urban area (North, South, East, West, Central)
  • Population: Zone population (50k-250k)
  • Rainfall: Daily rainfall in mm (Gamma distribution)
  • Temperature: Hourly temperature with seasonal variation
  • Season: Winter, Spring, Summer, Autumn
  • Water Usage: Realistic consumption patterns (L/day)

Realistic Patterns

  • Seasonal variations (higher usage in summer)
  • Daily patterns (peak at noon, low at night)
  • Weekly patterns (higher on weekdays)
  • Rainfall impact (reduced usage during rain)
  • Population-based scaling

πŸ”§ Configuration

Edit utils/config.py to customize:

# Data
ZONES = ['North', 'South', 'East', 'West', 'Central']
TRAIN_TEST_SPLIT = 0.8

# ML Models
LSTM_EPOCHS = 50
LSTM_BATCH_SIZE = 32

# DSS
WATER_SUPPLY_CAPACITY = 5000  # L/min
CRITICAL_THRESHOLD = 0.90
WARNING_THRESHOLD = 0.75
ALERT_THRESHOLD = 0.60

# Dashboard
DASHBOARD_UPDATE_INTERVAL = 10  # seconds

πŸ“ Usage Examples

Training Only

python main.py  # Complete training pipeline

Using Trained Models

from models.ml_models import MLModelsTrainer
from lstm.lstm_model import LSTMForecaster
import joblib

# Load models
lr_model = joblib.load('models/ml_models_lr.pkl')
lstm = LSTMForecaster()
lstm.load_model('models/lstm_model.h5')

# Make predictions
features = [[150000, 10.5, 25.3, 2, 14]]  # population, rainfall, temp, season, hour
prediction = lr_model.predict(features)

Generate Forecasts

from forecasting.forecasting_engine import ForecastingEngine

forecast_report = forecasting_engine.generate_forecast_report(
    all_zones_data=df,
    lstm_data=lstm_sequences
)

# Get area-specific forecast
north_forecast = forecast_report['zones']['North']
print(f"North Zone 7-day forecast: {north_forecast['ensemble_forecast']}")

Check Demand vs Supply

from decision_support.dss import DecisionSupportSystem

dss = DecisionSupportSystem(supply_capacity=5000)

analysis = dss.check_demand_vs_supply(
    current_demand=3500,
    forecasted_demand=4200
)

alert = dss.generate_alert(analysis, zone='Central')
print(alert['message'])  # Alert message based on utilization

πŸ› Troubleshooting

TensorFlow/CUDA Issues

# Install CPU version if GPU unavailable
pip install tensorflow-cpu

Streamlit Port Already in Use

streamlit run dashboard/dashboard.py --server.port 8502

Memory Issues During Training

Reduce LSTM_BATCH_SIZE in utils/config.py:

LSTM_BATCH_SIZE = 16  # Reduced from 32

πŸ“š Project Features Summary

βœ… Data Generation: Realistic 365-day water consumption dataset βœ… Preprocessing: Missing value handling, normalization, time-series formatting βœ… ML Models: Linear Regression, Random Forest with evaluation (MAE, RMSE) βœ… Deep Learning: LSTM for 7 and 30-day time-series forecasting βœ… Forecasting Engine: Area-wise predictions and peak demand detection βœ… Decision Support: Automated alerts, rationing plans, priority zones βœ… IoT Simulation: Real-time smart meters with background threading βœ… Dashboard: Advanced Streamlit UI with interactive Plotly charts βœ… Logging: Comprehensive application logging βœ… Model Persistence: Save/load trained models βœ… Ensemble Methods: Combines ML and DL for robust predictions βœ… Production Ready: Clean code, error handling, documentation

πŸ“„ License

This is an educational final-year engineering project.

πŸ‘¨β€πŸ’» Author

Developed as a comprehensive AI/ML engineering project demonstrating real-world system design and implementation.


Happy Water Forecasting! πŸ’§

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages