Skip to content

kraryal/Grid_Disruption_Analysis

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

11 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

โšก Grid Disruption Analysis

Python Flask License

๐Ÿ“Š Overview

Grid Disruption Analysis is a comprehensive Flask-based web application that visualizes and analyzes U.S. power grid outage data spanning from 2014 to 2023. This project combines interactive data visualization with advanced machine learning techniques to provide actionable insights for researchers, utility companies, and policymakers.

๐ŸŽฏ Target Audience

  • Energy researchers and analysts
  • Utility companies and grid operators
  • Policy makers and government agencies
  • Data science enthusiasts

โœจ Key Features

๐Ÿ“ˆ Interactive Visualizations

  • State-wise Monthly Heatmap: Track outage patterns across states and time
  • Hourly Outage Analysis: Identify peak disruption times
  • Choropleth Maps: Geographic visualization of outage distribution
  • Network Graphs: Visualize connections between outage events

๐Ÿค– Machine Learning Models

  • Forecasting: Prophet-based time series prediction for outage trends
  • Anomaly Detection: Isolation Forest algorithm to identify unusual events
  • Clustering Analysis: K-Means clustering to group states by outage patterns
  • Duration Prediction: Predictive models for outage duration estimation

๐Ÿ’ก Key Insights

  • Seasonal and temporal outage patterns
  • Regional vulnerability analysis
  • Peak disruption time identification
  • Grid resilience enhancement recommendations

๐Ÿ› ๏ธ Tech Stack

  • Backend: Flask (Python web framework)
  • Data Processing: Pandas, NumPy
  • Visualization: Plotly, Matplotlib, Seaborn
  • Machine Learning: Scikit-learn, Prophet
  • Network Analysis: NetworkX
  • Frontend: HTML, CSS, Bootstrap

๐Ÿš€ Quick Start

Prerequisites

# Check Python version (3.8+ required)
python --version

# Ensure pip is installed
pip --version

Installation

  1. Clone the repository
git clone https://github.com/kraryal/Grid_Disruption_Analysis.git
cd Grid_Disruption_Analysis
  1. Set up virtual environment (Recommended)
# Create virtual environment
python -m venv venv

# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
  1. Install dependencies
# Install from requirements.txt
pip install -r requirements.txt

# OR install manually if requirements.txt is missing
pip install flask pandas prophet plotly seaborn matplotlib networkx scikit-learn numpy
  1. Verify installation
python -c "import flask, pandas, prophet, plotly, seaborn, matplotlib, networkx, sklearn; print('โœ… All dependencies installed successfully!')"

๐Ÿ”ง Post-Installation Setup

1. Directory Structure Verification

# Ensure you're in the correct directory
ls -la
# You should see: CODE/ folder, README.md, etc.

# Navigate to CODE directory
cd CODE

# Verify Flask app exists
ls -la app.py

2. Data Setup (if required)

# If data folder doesn't exist, create it
mkdir -p data

# Verify data files are present
ls -la data/
# Should contain your grid outage datasets

3. Configuration Check

# Optional: Create a config check script (config_check.py)
import os
import sys

def check_setup():
    """Verify the application setup"""
    
    # Check if we're in the right directory
    if not os.path.exists('app.py'):
        print("โŒ app.py not found. Make sure you're in the CODE directory.")
        return False
    
    # Check data directory
    if not os.path.exists('data'):
        print("โš ๏ธ  Data directory not found. Creating...")
        os.makedirs('data', exist_ok=True)
    
    # Check templates directory
    if not os.path.exists('templates'):
        print("โš ๏ธ  Templates directory not found.")
        return False
    
    # Check static directory
    if not os.path.exists('static'):
        print("โš ๏ธ  Static directory not found.")
        return False
    
    print("โœ… Setup verification complete!")
    return True

if __name__ == "__main__":
    check_setup()

4. Environment Variables (Optional)

# Create .env file for configuration (optional)
cat > .env << EOF
FLASK_APP=app.py
FLASK_ENV=development
FLASK_DEBUG=1
PORT=5000
EOF

# Load environment variables
# On Windows:
set FLASK_APP=app.py
set FLASK_ENV=development

# On macOS/Linux:
export FLASK_APP=app.py
export FLASK_ENV=development

๐Ÿƒโ€โ™‚๏ธ Running the Application

Method 1: Direct Python Execution

# Navigate to CODE directory
cd CODE

# Run the Flask application
python app.py

# Expected output:
# * Running on http://127.0.0.1:5000
# * Debug mode: on
# * Restarting with stat
# * Debugger is active!

๐Ÿ–ฅ๏ธ Application Usage

Accessing the Application

# Local access
http://127.0.0.1:5000
# or
http://localhost:5000

# Network access (if running with --host=0.0.0.0)
http://YOUR_IP_ADDRESS:5000

API Endpoints (if available)

# Example API calls using requests library
import requests

# Get monthly trends for a specific state
response = requests.get('http://127.0.0.1:5000/api/monthly_trend?state=California')
data = response.json()

# Predict outage duration
payload = {
    'duration': 120,
    'customers_affected': 5000,
    'demand_loss': 250
}
response = requests.post('http://127.0.0.1:5000/api/predict', json=payload)
prediction = response.json()

Sample Usage Code

# Example: Programmatic access to core functions
from app import app

# Create application context
with app.app_context():
    # Example: Get data for specific state
    def get_state_data(state_name):
        # Your data processing logic here
        pass
    
    # Example: Run prediction model
    def predict_outage_duration(features):
        # Your ML prediction logic here
        pass

๐Ÿ”ง Development Setup

Setting up for Development

# Install development dependencies
pip install -r requirements-dev.txt

# Or install individual dev packages
pip install pytest flask-testing black flake8 isort

# Run tests (if available)
python -m pytest tests/

# Format code with Black
black app.py

# Check code style
flake8 app.py

# Sort imports
isort app.py

Creating Custom Configurations

# config.py - Custom configuration file
import os

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-secret-key'
    DEBUG = True
    TESTING = False
    
class ProductionConfig(Config):
    DEBUG = False
    SECRET_KEY = os.environ.get('SECRET_KEY')
    
class DevelopmentConfig(Config):
    DEBUG = True
    
class TestingConfig(Config):
    TESTING = True
    DEBUG = True

# Usage in app.py
# app.config.from_object('config.DevelopmentConfig')

๐Ÿ› Troubleshooting

Common Issues and Solutions

  1. Port Already in Use
# Find process using port 5000
lsof -i :5000  # Mac/Linux
netstat -ano | findstr :5000  # Windows

# Kill the process or use different port
python app.py --port 8000
  1. Module Not Found Errors
# Reinstall dependencies
pip install --force-reinstall -r requirements.txt

# Check Python path
python -c "import sys; print('\n'.join(sys.path))"

# Ensure virtual environment is activated
which python  # Should show venv path
  1. Data Loading Issues
# Debug data loading
import pandas as pd
import os

print("Current directory:", os.getcwd())
print("Files in data/:", os.listdir('data/') if os.path.exists('data/') else "Data directory not found")
  1. Template Not Found
# Verify template structure
ls -la templates/
# Should contain: index.html, about.html, etc.

Debug Mode

# Add debug prints to app.py
if __name__ == '__main__':
    print("๐Ÿš€ Starting Grid Disruption Analysis App...")
    print("๐Ÿ“ Current directory:", os.getcwd())
    print("๐Ÿ“Š Checking data availability...")
    
    app.run(debug=True, host='127.0.0.1', port=5000)

๐Ÿ“Š Data Management

Data File Structure

data/
โ”œโ”€โ”€ grid_outages_2014_2023.csv    # Main dataset
โ”œโ”€โ”€ state_coordinates.json        # Geographic data
โ”œโ”€โ”€ processed/                    # Processed datasets
โ”‚   โ”œโ”€โ”€ monthly_aggregated.csv
โ”‚   โ”œโ”€โ”€ hourly_patterns.csv
โ”‚   โ””โ”€โ”€ anomaly_scores.csv
โ””โ”€โ”€ models/                       # Saved ML models
    โ”œโ”€โ”€ prophet_model.pkl
    โ”œโ”€โ”€ isolation_forest.pkl
    โ””โ”€โ”€ kmeans_clusters.pkl

Data Processing Examples

# Example data processing script
import pandas as pd
from datetime import datetime

def load_and_preprocess_data():
    """Load and preprocess grid outage data"""
    
    # Load main dataset
    df = pd.read_csv('data/grid_outages_2014_2023.csv')
    
    # Convert date columns
    df['date'] = pd.to_datetime(df['date'])
    
    # Create additional features
    df['year'] = df['date'].dt.year
    df['month'] = df['date'].dt.month
    df['hour'] = df['date'].dt.hour
    df['day_of_week'] = df['date'].dt.dayofweek
    
    return df

# Usage
if __name__ == "__main__":
    data = load_and_preprocess_data()
    print(f"โœ… Loaded {len(data)} records")

๐Ÿ“ Complete Project Structure

Grid_Disruption_Analysis/
โ”œโ”€โ”€ CODE/
โ”‚   โ”œโ”€โ”€ app.py                     # Main Flask application
โ”‚   โ”œโ”€โ”€ requirements.txt           # Python dependencies
โ”‚   โ”œโ”€โ”€ config.py                  # Configuration settings
โ”‚   โ”œโ”€โ”€ models/                    # ML models directory
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ forecasting.py         # Prophet models
โ”‚   โ”‚   โ”œโ”€โ”€ anomaly_detection.py   # Isolation Forest
โ”‚   โ”‚   โ””โ”€โ”€ clustering.py          # K-Means clustering
โ”‚   โ”œโ”€โ”€ templates/                 # HTML templates
โ”‚   โ”‚   โ”œโ”€โ”€ base.html              # Base template
โ”‚   โ”‚   โ”œโ”€โ”€ index.html             # Homepage
โ”‚   โ”‚   โ”œโ”€โ”€ monthly_trend.html     # Monthly analysis
โ”‚   โ”‚   โ”œโ”€โ”€ predict.html           # Prediction interface
โ”‚   โ”‚   โ”œโ”€โ”€ heatmap.html           # State heatmap
โ”‚   โ”‚   โ”œโ”€โ”€ choropleth.html        # Geographic map
โ”‚   โ”‚   โ”œโ”€โ”€ hourly_heatmap.html    # Hourly patterns
โ”‚   โ”‚   โ”œโ”€โ”€ network_graph.html     # Network visualization
โ”‚   โ”‚   โ”œโ”€โ”€ anomaly.html           # Anomaly detection
โ”‚   โ”‚   โ”œโ”€โ”€ clustering.html        # State clustering
โ”‚   โ”‚   โ””โ”€โ”€ about.html             # About page
โ”‚   โ”œโ”€โ”€ static/                    # Static files
โ”‚   โ”‚   โ”œโ”€โ”€ css/
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ style.css          # Custom styles
โ”‚   โ”‚   โ”œโ”€โ”€ js/
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ app.js             # JavaScript functionality
โ”‚   โ”‚   โ””โ”€โ”€ images/                # Images and icons
โ”‚   โ”œโ”€โ”€ data/                      # Dataset files
โ”‚   โ”‚   โ”œโ”€โ”€ grid_outages_2014_2023.csv
โ”‚   โ”‚   โ””โ”€โ”€ processed/             # Processed data
โ”‚   โ””โ”€โ”€ utils/                     # Utility functions
โ”‚       โ”œโ”€โ”€ __init__.py
โ”‚       โ”œโ”€โ”€ data_processing.py     # Data manipulation
โ”‚       โ””โ”€โ”€ visualization.py       # Chart generation
โ”œโ”€โ”€ tests/                         # Test files
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ test_app.py               # App tests
โ”‚   โ””โ”€โ”€ test_models.py            # Model tests
โ”œโ”€โ”€ docs/                         # Documentation
โ”‚   โ”œโ”€โ”€ api.md                    # API documentation
โ”‚   โ””โ”€โ”€ deployment.md             # Deployment guide
โ”œโ”€โ”€ .env.example                  # Environment variables template
โ”œโ”€โ”€ .gitignore                    # Git ignore rules
โ”œโ”€โ”€ requirements.txt              # Production dependencies
โ”œโ”€โ”€ requirements-dev.txt          # Development dependencies
โ”œโ”€โ”€ Dockerfile                    # Docker configuration
โ”œโ”€โ”€ docker-compose.yml           # Docker Compose setup
โ”œโ”€โ”€ README.md                     # This file
โ””โ”€โ”€ LICENSE                       # License information

๐Ÿš€ Advanced Usage

Custom Model Training

# train_models.py - Script to retrain models with new data
from models.forecasting import ProphetForecaster
from models.anomaly_detection import AnomalyDetector
from utils.data_processing import load_and_preprocess_data

def retrain_models():
    """Retrain all ML models with latest data"""
    
    # Load latest data
    data = load_and_preprocess_data()
    
    # Retrain forecasting model
    forecaster = ProphetForecaster()
    forecaster.fit(data)
    forecaster.save('models/prophet_model_updated.pkl')
    
    # Retrain anomaly detection
    detector = AnomalyDetector()
    detector.fit(data)
    detector.save('models/isolation_forest_updated.pkl')
    
    print("โœ… All models retrained successfully!")

if __name__ == "__main__":
    retrain_models()

Batch Processing

# batch_analysis.py - Process multiple states or time periods
def batch_analyze_states(states_list):
    """Analyze multiple states in batch"""
    results = {}
    
    for state in states_list:
        print(f"๐Ÿ”„ Processing {state}...")
        # Your analysis logic here
        results[state] = analyze_state(state)
    
    return results

# Usage
states = ['California', 'Texas', 'New York', 'Florida']
batch_results = batch_analyze_states(states)

๐Ÿ‘ฅ Team

Team 155 - Data Analysis Initiative

  • Krishna Aryal - @kraryal - Project Lead & Backend Development
  • Crystal Vandekerkhove - Data Analysis & Visualization
  • Jinesh Patel - Machine Learning & Modeling

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ”ฎ Roadmap

  • Real-time data integration with utility APIs
  • Docker containerization for easy deployment
  • RESTful API endpoints for external integration
  • Mobile-responsive UI improvements
  • Advanced ML model comparison dashboard
  • Automated testing and CI/CD pipeline
  • Performance optimization and caching
  • Multi-language support

๐Ÿ“ž Support

Need help? Here's how to get support:


โญ Star this repository if you find it helpful!

Made with โค๏ธ by Team 155

================================================================================

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published