Skip to content

Repository files navigation

GridMind ⚡

Demo: Gridmind

AI-powered electrical network analysis, visualization, and automation.

GridMind is an intelligent platform for power system engineers, operators, and researchers. It combines an interactive graph-based visualization frontend with a comprehensive Python analysis backend — plus an AI agent that answers natural-language questions about your network.


Features

🕸️ Interactive Network Visualization

  • Force-directed & layout engines — Cola, CoSE, BFS, circle layouts via Cytoscape.js
  • Zoom, pan, search, filter — Explore networks of any size (14 to 70,000+ buses)
  • Multi-layer overlays
    • Topology layer — articulation points & bridge edges (red highlights)
    • Violations layer — buses flagged by the rule engine (orange)
    • Path layer — shortest path between any two buses (cyan)
    • Voltage layer — nodes coloured by per-unit voltage vs limits
  • Export to PNG — one-click screenshot of the graph canvas

📊 Power System Analysis

Capability Description
Power Flow AC/DC power flow using pandapower
Contingency Analysis N-1 / N-2 screening and worst-case ranking
Optimal Power Flow Economic dispatch, LMP analysis, congestion ranking
Load Shedding Infeasibility analysis via minimum load curtailment
Topology Analysis Connectivity, articulation points, bridges, cycles, feeder zones, redundancy
Rule Engine Structural linting — connectivity, parameter, and design rule checks
SCADA / PMU Real-time data ingestion, state estimation (WLS), alarm engine
GNN Inference Graph Neural Network for fast state prediction and contingency screening

🤖 AI Agent

A LangChain-powered ReAct agent with 60+ tools that can answer natural-language questions about your network:

"What happens if bus 4 goes down?"
"Which lines are overloaded?"
"Rank the top 5 worst N-1 contingencies."
"Find the cheapest redispatch to relieve congestion."

The agent returns structured responses with highlighted nodes/edges on the visualisation canvas.

🧪 Agent Evaluation (RAGAS)

The agent is evaluated using RAGAS — the industry-standard framework for LLM application evaluation. The evaluation suite measures:

Metric Description Score Range
ToolCallAccuracy Did the agent call the correct tool with the right arguments? 0.0–1.0
Faithfulness Are the agent's claims grounded in actual tool observations? 0.0–1.0

Quick run:

# Full suite (all categories, slow — includes LLM judge)
python -m agent.evaluation.run_evaluation

# Fast mode (ToolCallAccuracy only, no LLM calls)
python -m agent.evaluation.run_evaluation --fast

# Filter by category
python -m agent.evaluation.run_evaluation --fast --category topology

# Output JSON for CI pipelines
python -m agent.evaluation.run_evaluation --fast --reporter json --output eval-report.json

Results (topology domain, 3 cases):

ToolCallAccuracy    1.000   ████████████████████
Faithfulness        1.000   ████████████████████
Pass Rate           100%

Test cases are defined in YAML under agent/evaluation/cases/ across 8 domains: topology, powerflow, contingency, OPF, SCADA, GNN, and mixed.

For full evaluation documentation, see AGENT_EVALUATION.md.

🗺️ Schematic Import

Upload a single-line diagram (SLD) image — GridMind uses computer vision (YOLO-based detection) to recognise components and reconstruct the network model automatically.

💾 Grid Management

Save, load, edit, and organise named grid snapshots in MongoDB with GridFS (no 16 MB limit).


Quick Start

Prerequisites

  • Python 3.13+
  • MongoDB (local or remote)
  • (Optional) Azure OpenAI credentials for the AI agent

Setup

# 1. Clone and enter the repository
git clone <repo-url>
cd GridMind

# 2. Create a Python virtual environment
python -m venv .venv
.venv\Scripts\Activate.ps1

# 3. Install Python dependencies
pip install -r requirements.txt

# 4. Install frontend dependencies
cd frontend
npm install
cd ..

# 5. Configure environment
#    Copy .env.example to .env and fill in the values

Run

# Start both servers with one command:
.\start.ps1

# Or start them separately:
# Terminal 1 — Backend API
uvicorn api.main:app --reload --port 8000

# Terminal 2 — Frontend UI
cd frontend
npm run dev

Open http://localhost:5173 in your browser.


Project Structure

GridMind/
├── agent/                       # AI agent (LangChain ReAct)
│   ├── grid_agent.py            # Agent orchestration + response model
│   ├── planner.py               # System prompt
│   ├── executor.py              # Synchronous tool executor
│   ├── tool_registry.py         # Central tool catalogue
│   ├── tools/                   # 60+ LangChain tool definitions
│   └── evaluation/              # RAGAS-based agent evaluation
│       ├── suite.py             # Evaluation orchestrator
│       ├── config.py            # RAGAS LLM & metric setup
│       ├── trace_adapter.py     # AgentResponse → RAGAS format
│       ├── run_evaluation.py    # CLI entry point
│       ├── cases/               # YAML test cases (8 domains)
│       └── reporters/           # Console, JSON, HTML output
│       ├── topology_tools.py    # Graph topology analysis
│       ├── powerflow_tools.py   # Power flow simulation
│       ├── contingency_tools.py # N-1/N-2 contingency analysis
│       ├── opf_tools.py         # Optimal power flow
│       ├── load_shedding_tools.py
│       ├── scada_tools.py       # SCADA/PMU data queries
│       ├── gnn_tools.py         # GNN inference tools
│       ├── rule_tools.py        # Rule engine wrapper
│       ├── query_tools.py       # General graph queries
│       └── extended_tools.py    # Extended analysis tools
│
├── api/                         # FastAPI backend
│   ├── main.py                  # App entry-point + CORS
│   ├── dependencies.py          # Engine cache / loader
│   ├── db.py                    # MongoDB client
│   └── routers/
│       ├── agent.py             # POST /api/agent/query
│       ├── cases.py             # GET /api/cases
│       ├── graph.py             # GET /api/graph/{case}
│       ├── topology.py          # GET /api/topology/{case}
│       ├── rules.py             # GET /api/rules/{case}
│       ├── path.py              # GET /api/path/{case}
│       ├── grids.py             # CRUD /api/grids
│       ├── schematics.py        # POST /api/schematics/import
│       ├── powerflow.py         # Power flow endpoints
│       ├── contingency.py       # Contingency endpoints
│       ├── opf.py               # OPF endpoints
│       ├── scada.py             # SCADA endpoints
│       ├── gnn.py               # GNN endpoints
│       └── load_shedding.py     # Load shedding endpoints
│
├── frontend/                    # React + Vite + Tailwind CSS
│   └── src/
│       ├── api/                 # Axios client + TypeScript types
│       ├── components/          # React components
│       │   ├── NetworkGraph.tsx     # Cytoscape.js graph canvas
│       │   ├── TopBar.tsx           # Case selector, layout buttons
│       │   ├── Sidebar.tsx          # Search, filter, path tools
│       │   ├── DetailsPanel.tsx     # Node/edge detail panel
│       │   ├── AgentPanel.tsx       # Chat-style agent interface
│       │   ├── ViolationsPanel.tsx  # Rule violations overlay
│       │   ├── PowerFlowPanel.tsx   # Power flow controls
│       │   ├── ContingencyDashboard.tsx
│       │   ├── OPFDashboard.tsx
│       │   ├── Legend.tsx
│       │   ├── GridManager.tsx      # Saved grid management
│       │   ├── GridEditor.tsx       # In-browser grid editing
│       │   ├── SchematicImporter.tsx
│       │   ├── scada/               # SCADA dashboard
│       │   └── gnn/                 # GNN dashboard
│       ├── hooks/               # React Query data hooks
│       ├── context/             # Global visualization state
│       ├── lib/                 # Cytoscape styles & layout config
│       └── types/               # TypeScript type definitions
│
├── services/                    # Python analysis services
│   ├── importers/               # MATPOWER .m file parser
│   ├── graph/                   # NetworkX graph engine
│   ├── topology_analysis/       # Structural graph analysis
│   ├── rule_engine/             # Engineering rule checks
│   ├── powerflow/               # pandapower power flow
│   ├── contingency/             # Contingency analysis
│   ├── opf/                     # Optimal power flow
│   ├── load_shedding/           # Load curtailment analysis
│   ├── scada/                   # SCADA/PMU ingestion pipeline
│   └── gnn/                     # Graph Neural Network inference
│
├── datasets/matpower/           # 100+ MATPOWER case files (.m)
├── weights/                     # Trained model weights
├── sld2matpower/                # Schematic-to-MATPOWER converter
│
├── start.ps1                    # Windows PowerShell launcher
├── start.bat                    # Windows CMD launcher
├── Dockerfile                   # Container build
├── requirements.txt             # Python dependencies
└── VISUALIZATION.md             # Visualization feature guide

API Overview

Method Endpoint Description
GET /api/health Health check
GET /api/cases List available MATPOWER case files
GET /api/graph/{case} Cytoscape.js-compatible graph data
GET /api/topology/{case} Full topology analysis
GET /api/topology/{case}/metrics Network metrics only
GET /api/topology/{case}/validation Structural validation
GET /api/rules/{case} Full rule-engine report
GET /api/rules/{case}/{category} Rules by category
GET /api/path/{case}?from_bus=&to_bus= Shortest path
POST /api/agent/query Natural-language agent query
GET /api/agent/tools List available agent tools
POST /api/schematics/import Import SLD image → network model
POST /api/grids Save a grid snapshot
GET /api/grids List saved grids
GET /api/grids/{id} Get saved grid
PATCH /api/grids/{id} Update grid metadata
DELETE /api/grids/{id} Delete a grid
GET /api/grids/{id}/graph Saved grid as Cytoscape graph

Interactive API docs: http://localhost:8000/docs


AI Agent

The GridMind agent uses LangChain's ReAct framework with Azure OpenAI (GPT-4o-mini by default). It has access to 60+ domain-specific tools organised into categories:

  • Topology — critical nodes, bridges, islands, downstream tracing, failure simulation
  • Power Flow — run power flow, voltage/overload violations, summary reports
  • Contingency — N-1 screening, worst-case ranking, secure status
  • OPF — optimal dispatch, LMP, congestion ranking, redispatch suggestions
  • Load Shedding — minimum curtailment, resilience summary
  • SCADA — live voltage, alarms, frequency, measurement history
  • GNN — fast state prediction, contingency screening, topology anomaly detection
  • Rules — run all engineering rule checks
  • Query — shortest path, bus details, hub/load bus discovery
  • Extended — upstream tracing, supply chains, feeder zones, voltage filtering

Configuration

Set the following environment variables in .env:

AZURE_OPENAI_ENDPOINT=https://your-resource.openai.azure.com/
AZURE_OPENAI_API_KEY=your-key
AZURE_OPENAI_DEPLOYMENT_NAME=your-deployment
AZURE_OPENAI_API_VERSION=api-version
GRIDMIND_MAX_ITERATIONS=max-iteration
GRIDMIND_AGENT_TIMEOUT=agent-timeout

Graph Neural Network

GridMind includes a PowerGridGNN model for fast power system state prediction, trained with PyTorch Geometric. Key features:

  • Message-passing architecture — GAT or PI-EVGNN layers
  • Physics-informed loss — optional AC power balance residuals
  • N-1 / N-2 contingency screening — fast state prediction without full AC power flow
  • Topology anomaly detection — flag unexpected graph changes
# Train a model
python train_gnn.py --cases case14,case30,case118 --epochs 100

# With physics-informed loss (PI-EVGNN)
python train_gnn.py --cases case14,case30 --epochs 50 --layer-type evgnn --physics-loss

Container Deployment

docker build -t gridmind .
docker run -p 8080:8080 gridmind

Tech Stack

Layer Technology
Backend Python 3.13, FastAPI, pandapower, NetworkX
Frontend React 19, TypeScript, Vite, Tailwind CSS 4
Graph Cytoscape.js, cytoscape-cola, cytoscape-fcose
AI Agent LangChain, Azure OpenAI (GPT-4o-mini)
GNN PyTorch, PyTorch Geometric
Database MongoDB + GridFS
Computer Vision YOLO (schematic import)
Container Docker

License

GNU Affero General Public License v3.0 (AGPL-3.0) — see LICENSE for details.

Releases

Packages

Contributors

Languages