# Project export: GridVeda

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: TreeHacks 2026
- Tagline: GridVeda gives powerline operators predictive failure detection at edge. Ensemble AI monitors 20 transformers with real-time health scoring + natural lang diagnostics; all autonomous on NVIDIA Jetson.
- Devpost: https://devpost.com/software/gridveda
- GitHub: https://github.com/TheRaven5520/GridVeda
- Demo: https://v0-gridveda.vercel.app/
- Video: https://www.youtube.com/embed/xun8Srjo-jY?enablejsapi=1&hl=en_US&rel=0&start=80&version=3&wmode=transparent
- Result: winner ([Stanford Ecopreneurship] Sustainability: Best prototyping process)
- Team: 1 GitHub contributor(s) — TheRaven5520 (13 commits)

## Devpost submission (written by the team)

### Inspiration

Grid operators work in high-stakes environments where failures cascade fast. Today, 46% of U.S. distribution infrastructure is at or beyond its useful life, contributing to an annual economic loss of $150 billion. The DOE warns that without intervention, the risk of major outages could increase 30-fold by 2030. When a single transformer fails under these conditions, often due to the overloading seen in 34% of recent asset failures, it can knock out substations and leave communities dark for days. Power interruptions are becoming more frequent and more severe. Since 2000, the number of major weather-related outages has increased dramatically, with extreme weather now responsible for over 80% of large-scale blackouts in the U.S. A single transformer failure can overload neighboring assets, knock out substations, and leave entire communities without power for days. Recent events, from the 2021 Texas grid crisis to the 2023 North Carolina substation attacks and extreme weather-driven outages, reveal a common reality: we are still reacting to failures instead of predicting them. Growing up across California, Oregon, and Maryland, our team has witnessed firsthand how fragile infrastructure can amplify disaster impacts, from wildfire-driven outages in the West to storm-related grid disruptions on the East Coast. These experiences reinforced the need for on-device intelligence that continues operating even when connectivity is unreliable: especially during storms, heat waves, or grid stress events. Our goal with GridVeda: AI-Powered Grid Intelligence is to empower operators with real-time, AI-driven decision support at the edge - detecting transformer degradation early, classifying fault types, estimating time-to-failure, and guiding mitigation, all without requiring cloud dependency.

### What it does

GridVeda is an AI-powered early warning system for electrical transformers that runs on-site at substations, predicting failures before blackouts occur. Real-Time Transformer Monitoring: Monitors 20 transformers simultaneously via two AI pipelines Physics Informed ETT Anomaly Analysis ETT detector processes sensor readings every 15 minutes (oil temp + 6 load channels) Uses feature engineering to compute 36 physics features: thermal stress, Joule heating, insulation aging Four neural network based Gradient Boosting Ensemble (LightGBM, CatBoost, Random Forest, XGBoost) architecture Alerts operators at >50% risk to schedule gas testing based on Mild and High stakes Quantum-Classical Fault Diagnosis Implemented 6-qubit variational quantum circuit with 72 trainable parameters across 4 entangled layers Trained with gradient-free Nelder-Mead optimization to avoid barren plateaus in 64-dimensional Hilbert space Architected quantum-classical hybrid meta-ensemble merging Born rule measurement probabilities with IEEE C57.104 standards Integrated tri-method plurality voting: quantum predictions + Rogers Ratios + Duval Triangle classification Built 2nd weighted ensemble across XGBoost, LightGBM, CatBoost, and RandomForest with confidence-aware routing Developed 8→4 class probability mapping using modular arithmetic aggregation of quantum measurement outcomes Implemented strategic label transformation and prediction consensus mechanisms for robust classification DGA Summary: 98.09% ± 0.80% accuracy, 96.99% ± 2.07% F1-macro, 98.08% ± 0.75% F1-weighted Conversational Grid Interface Nemotron Nano 4B provides plain-English explanations of fault diagnostics and risk scores through live visual feedback loop of the active dashboard interface Answers context-aware queries like "Why is T047 flagged as high risk?" by analyzing current screen state and transformer-specific DGA patterns in real-time Offers interactive guidance that responds to displayed data, helping operators understand which gas concentrations and ratios drove specific fault predictions Supports voice-enabled hands-free operation for field technicians to query diagnostics, request explanations, and navigate the system without manual input Web-Grounded Spatial Intelligence Perplexity auto-searches "transformer discharge failures [C2H2 elevated] Texas 2024" when faults are detected. Retrieves NERC reports and regional failure data at ~1,200 tok/s. Cross-references DGA signatures against historical recalls and weather-correlated failures. Identifies similar fault progressions from past incidents. Renders interactive 3D transformer models with real-time fault probability heat maps. Overlays risk zones on bushings, windings, tap changers and other various components. Maps gas diffusion physics to spatial failure zones using thermal signatures. Localizes acetylene (>700°C arcing) to probable discharge points. Spins up isolated virtual environments within the web app using three.js for fault simulation. Operators test "what-if" scenarios, worldwide past occurrences and model fault progression. Executes sandboxed Python/NumPy environments for custom DGA scripts. Engineers run proprietary algorithms without leaving the browser. Responsible AI Built on fine-tuned open-source GPT-oss models to explain neural network decisions and fault predictions in plain language. Breaks down how quantum ensemble, XGBoost, DGA methods, etc. reached specific diagnoses. Provides interactive onboarding for new operators through adaptive tutorials on transformer diagnostics. Explains DGA interpretation, Rogers Ratios, Duval Triangle classification, etc. based on current workflow context. Maintains audit trails of predictions, model weights and decision factors for regulatory compliance. - Full traceability from input features through ensemble voting to final risk scores. Edge AI Without Cloud Runs entirely on RTX 5090 (dev) or Jetson Orin Nano Super (25W field deployment) Works during storms/outages when connectivity fails Direct connection to raw sensory transformer units GPT-4 orchestrates training, bias monitoring, human-in-the-loop safeguards

### How we built it

1. NVIDIA Edge AI Stack Deployed Nemotron Nano 4B, Perplexity Sonar, GPT-oss on RTX 5090 alongside two gradient boosting ensembles INT8 quantization + TensorRT optimization for 25W Jetson Orin field deployment Ollama continuous batching hits 200-400ms latency, cuQuantum provides 5-10× quantum speedup Zero cloud dependency for core detection 2. Real-Time Telemetry FastAPI + WebSocket streams 180 data points (20 transformers × 9 channels) every 2 seconds Next.js dashboard displays live health scores, risk gauges, AI predictions Fault injection simulates thermal runaway, acetylene spikes, cascades for training Push-based architecture for sub-second detection 3. Screen-Aware Conversational AI HTML5 Canvas snapshots dashboard every 5s; Tesseract OCR extracts IDs and alerts Nemotron processes visual + parsed JSON, system-prompted with IEEE C57.104 standards Translates SHAP values to plain English, responds to queries like "Why is T047 high risk?" Web Speech API for hands-free voice control 4. Perplexity Sonar: Spatial Fault Visualization Auto-triggers on faults, queries "transformer discharge failures [C2H2 elevated] Texas 2024" at ~1,200 tok/s Retrieves NERC reports, recalls, weather events with citation tracking Python parses CAD files (STEP/IGES) via Open CASCADE → OBJ → Three.js 3D rendering Gas diffusion physics maps acetylene (>700°C arcing) to bushings/tap changers WebGL volumetric heat maps fuse chemistry + Perplexity failure frequencies 5. Dual Gradient Boosting Ensembles ETT-NN: XGBoost/LightGBM/CatBoost/RF (150 each) on 36 physics features—thermal stress, Joule heating, Arrhenius aging. RobustScaler preprocessing, 3-fold CV weighting, outputs 0-100% risk scores. DGA-NN: XGBoost/LightGBM/CatBoost/RF (200 each) on gas concentrations + Rogers ratios + Duval percentages. StandardScaler normalization, soft voting for fault prediction, 2:1 meta-voting with quantum ensemble. 6. Quantum Fault Classifier 6-qubit VQC: Hadamard → 9-feature encoding → 4 variational layers (72 params) → CNOT ring Tri-method voting: Quantum + Rogers Ratio + Duval Triangle → plurality across 8 fault classes cuQuantum parallelizes 64 state amplitudes on CUDA, 50-100ms inference Consensus scoring: unanimous fault=60-90%, split=30-50%, normal=5-15% 7. GPT-4 Responsible AI Adaptive tutorials (physics for techs, architecture for engineers) Layered explanations: voting analogies → circuit details → LaTeX derivations Bias monitoring, A/B testing, human-in-the-loop enforcement for critical actions 8. Multi-Model Fusion Parallel XGBoost/LightGBM/CatBoost/RandomForest ensembles for ETT anomaly detection Quantum VQC (72 parameters, 6 qubits) combines with classical gradients via tri-method plurality voting including 2nd Gradient Boosting Ensemble, Rogers Ratios and Duval TriangleDGA fault classification with weighted soft voting Async parallel execution of quantum/boosting/LLM without blocking TensorRT quantization for production deployment

### Challenges we ran into

Running 5+ AI models simultaneously on 25W Jetson required aggressive memory management. Conflicts between cuQuantum state vectors, gradient boosting trees, and LLM layers forced us to build careful GPU allocation with TensorRT quantization to maintain edge operation. Coordinating dual data streams—continuous ETT monitoring and on-demand DGA testing (H2, CH4, C2H2, C2H4, C2H6, CO, CO2 concentrations)—into unified risk scores was challenging. Balancing quantum-classical ensemble weights through cross-validated F1 scores while maintaining high precision required iterative tuning. First time integrating two completely different pipelines (time-series anomaly detection + gas chemistry classification) into one diagnostic system. Physics-informed feature engineering meant translating Arrhenius aging, Joule heating, and gas diffusion into robust numerical features. Edge cases like division-by-zero in Rogers ratios needed epsilon regularization. We had to validate that our 36 ETT features actually captured fault mechanisms better than raw sensors. Getting quantum inference under 100ms on edge hardware pushed cuQuantum hard. Hand-tuning 72 variational parameters across 4 layers and minimizing CNOT depth took extensive experimentation. Making the tri-method ensemble (quantum + Rogers + Duval) produce coherent predictions required principled tiebreaking rules. Real-time 3D fault visualization was complex—parsing CAD files, computing gas diffusion PDEs over voxel grids, fusing chemistry with Perplexity failure data via Bayesian inference, and rendering volumetric heat maps in Three.js with WebGL shaders while maintaining smooth framerates. Ensuring zero-cloud resilience meant building graceful degradation when Perplexity/GPT-4 are unreachable. Nemotron handles core diagnostics offline while we cache Perplexity results in Redis with priority queuing for fault-triggered research.

### Accomplishments we're proud of

5 AI models + Neural Networks running simultaneously on a single RTX 5090 -- quantum VQC, dual gradient boosting ensembles (ETT + DGA), and LLM architectures cooperating in real-time 5 AI models + Neural Networks running simultaneously on a single RTX 5090 -- quantum VQC, dual gradient boosting ensembles (ETT + DGA), and LLM architectures cooperating in real-time 100% NVIDIA-native edge story - Nemotron + cuQuantum VQC + gradient boosting ensembles all run without any cloud dependency, deployable on a $249 Jetson 100% NVIDIA-native edge story - Nemotron + cuQuantum VQC + gradient boosting ensembles all run without any cloud dependency, deployable on a $249 Jetson Sub-second anomaly detection - 0.21ms quantum inference per sample, 50-200ms ETT ensemble across 20 transformers with ensemble confidence scoring Sub-second anomaly detection - 0.21ms quantum inference per sample, 50-200ms ETT ensemble across 20 transformers with ensemble confidence scoring Perplexity Sonar at ~1,200 tok/s - enabling real-time incident research and 3D spatial fault visualization that's fast enough for grid decisions Perplexity Sonar at ~1,200 tok/s - enabling real-time incident research and 3D spatial fault visualization that's fast enough for grid decisions Web-grounded spatial intelligence - Perplexity Sonar retrieves NERC reports and failure case studies, rendering 3D transformer models with physics-based fault probability heat maps Web-grounded spatial intelligence - Perplexity Sonar retrieves NERC reports and failure case studies, rendering 3D transformer models with physics-based fault probability heat maps Voice-controlled grid monitoring - fully hands-free operation for field technicians Voice-controlled grid monitoring - fully hands-free operation for field technicians 98% DGA fault classification accuracy with 97% F1-score - Quantum-classical hybrid ensemble achieves 98.09% ± 0.80% accuracy across 5-fold cross-validation, with 96.99% macro F1 and 98.08% weighted F1 on multi-class transformer diagnostics 98% DGA fault classification accuracy with 97% F1-score - Quantum-classical hybrid ensemble achieves 98.09% ± 0.80% accuracy across 5-fold cross-validation, with 96.99% macro F1 and 98.08% weighted F1 on multi-class transformer diagnostics Interactive Real-Time Dashboard: The web-based monitoring interface provides live transformer health visualization with color-coded risk indicators, gas concentration trends, and fault probability heat maps updated in real-time as new sensor data arrives. Built with React and D3.js, the dashboard displays ETT anomaly scores, DGA fault classifications, and ensemble confidence metrics across all monitored transformers simultaneously. Operators can drill down into individual units to view historical gas chemistry plots, Rogers Ratio trends, and Duval Triangle trajectories over time. The interface integrates the conversational AI overlay where Nemotron Nano 4B answers queries like "Why is T047 high risk?" by analyzing the current screen state, making complex diagnostics accessible to field technicians without deep expertise in quantum machine learning or IEEE standards. Interactive Real-Time Dashboard: The web-based monitoring interface provides live transformer health visualization with color-coded risk indicators, gas concentration trends, and fault probability heat maps updated in real-time as new sensor data arrives. Built with React and D3.js, the dashboard displays ETT anomaly scores, DGA fault classifications, and ensemble confidence metrics across all monitored transformers simultaneously. Operators can drill down into individual units to view historical gas chemistry plots, Rogers Ratio trends, and Duval Triangle trajectories over time. The interface integrates the conversational AI overlay where Nemotron Nano 4B answers queries like "Why is T047 high risk?" by analyzing the current screen state, making complex diagnostics accessible to field technicians without deep expertise in quantum machine learning or IEEE standards.

### What we learned

Ensemble AI Improves Reliability No single model was consistently correct. Our quantum VQC occasionally misclassified edge cases, but the Nemotron predictors compensated. A weighted ensemble produced more stable, higher-confidence results than any standalone model. Edge AI Is Essential for Infrastructure In real grid failures, internet connectivity cannot be assumed. Deploying Nemotron and anomaly detection locally on NVIDIA Jetson eliminates cloud dependency and ensures continuous operation during storms or cascading outages. Inference Speed Directly Impacts Safety Reducing trend prediction latency from 30 seconds to under 1 second can materially change outcomes in a cascading grid event. Faster inference enables earlier load shedding and preventive intervention. Web-Grounded Context Enhances Decision-Making Local models understand transformer chemistry and fault theory, but integrating Perplexity Sonar adds real-world awareness—recent incidents, recalls, weather threats, and regulatory updates—improving operator situational awareness. Modular Architecture Enables Rapid Iteration Separating subsystems (telemetry ingestion, ensemble inference, agent interface, web intelligence layer) allowed us to experiment with model weighting, async fusion, and GPU optimization without destabilizing the full system. Infrastructure AI Requires Security by Design Because grid systems are critical infrastructure, we implemented strict input validation, authentication controls, and controlled model invocation to prevent misuse or unsafe command generation.

### What's next

Live Edge Demonstrations with NVIDIA Hardware: We plan to optimize and deploy GridVeda on NVIDIA Jetson Orin Nano Super for fully autonomous substation deployment. This includes TensorRT quantization of Nemotron to achieve 2–3x faster inference and production-grade reliability, proving that edge AI can deliver enterprise performance in the field. Expanded Web-Grounded Intelligence with Perplexity Sonar: We will deepen our integration with Perplexity's Sonar API to provide real-time incident correlation—automatically linking transformer anomalies to NERC reports, weather events, and regional outage data during live operations. Our goal is to showcase GridVeda as the first grid intelligence system that combines edge AI with continuously updated global infrastructure knowledge. Utility Pilot Programs & Field Validation: We intend to partner with regional utility providers to deploy GridVeda alongside real SCADA feeds. Initial pilots will focus on early transformer degradation detection and substation-level anomaly triage, collecting operational data to validate failure prediction accuracy and refine our models against real-world grid conditions. Conference & Research Publication: We are preparing a technical paper detailing our hybrid ensemble architecture (Quantum VQC + Ensemble-based NN + LLM) for submission to infrastructure resilience and applied AI conferences. Showcasing GridVeda at technical venues will help bridge academia, utilities, and industry while contributing to the broader research community. Federated Learning Across Utilities: Next iterations will introduce federated training across multiple substations—allowing utilities to improve anomaly detection collectively without sharing sensitive operational data. This privacy-preserving approach enables grid-wide learning while respecting the security requirements of critical infrastructure. Integration with SCADA systems and IEC 61850 protocols will enable real-time data ingestion from substation sensors, replacing simulated datasets with live transformer telemetry for continuous model updates and immediate fault detection at scale. From Hackathon to Company: Beyond TreeHacks, we are actively exploring pathways to turn GridVeda into a venture-backed startup. We plan to pursue the Human Capital Fellowship for long-term company building, Neo Accelerator for early-stage product-market validation and strategic partnerships with NVIDIA and infrastructure-focused investors. Our vision is to evolve GridVeda from a 36-hour prototype into a deployable AI infrastructure platform protecting national energy systems.

## README (from the GitHub repository)

# GridVeda — AI-Powered Grid Intelligence

Real-time transformer fault monitoring powered by ensemble ML, quantum variational circuits, and web-grounded research. Built on NVIDIA infrastructure end-to-end.

## Architecture

```
┌─────────────────────────────────────────────────────────┐
│  Frontend (React + Vite)                                │
│  ├── WebSocket ← Real-time telemetry every 2s           │
│  ├── REST → /api/chat (Nemotron 4B via Ollama)          │
│  ├── REST → /api/search (Perplexity Sonar)              │
│  ├── REST → /api/predict (Quantum VQC)                  │
│  └── 3D CAD Visualizer (Three.js, 47 components)        │
└──────────────────────┬──────────────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────────────┐
│  FastAPI Backend (main.py :8000)                         │
│  ├── WebSocket /ws/telemetry (2s broadcast loop)         │
│  │                                                       │
│  ├── AI Pipeline                                         │
│  │   ├── ETT Risk Engine (XGBoost/LightGBM/CatBoost/RF) │
│  │   ├── DGA Fault Classifier (Rogers + Duval + VQC)     │
│  │   ├── Quantum VQC (6 qubits, 4 variational layers)   │
│  │   └── NemotronChat → Ollama :11434 (local GPU)        │
│  │                                                       │
│  ├── Integrations                                        │
│  │   └── PerplexityChat → Sonar API (web-grounded)       │
│  │                                                       │
│  └── 20 monitored transformers with full DGA profiles    │
└──────────────────────┬──────────────────────────────────┘
                       │
┌──────────────────────▼──────────────────────────────────┐
│  Ollama (:11434)                                         │
│  └── nemotron-nano-4b-instruct (NVIDIA open model)       │
└─────────────────────────────────────────────────────────┘
```

## Quick Start

```bash
# 1. Install dependencies and start the backend
cd backend && pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 8000

# 2. Start the React frontend
cd ../frontend && npm install && npm run dev

# 3. (Optional) Enable local Nemotron chat
ollama pull nemotron-nano-4b-instruct && ollama serve

# 4. (Optional) Enable Perplexity web search
export PERPLEXITY_API_KEY=pplx-xxxx
```

> All core monitoring features work without external API keys.

## AI Pipeline

GridVeda uses a 4-stage pipeline that activates progressively based on risk severity.

| Stage | Component | Role | Accuracy |
|-------|-----------|------|----------|
| 1 | **ETT Sensors** | Stream 7 channels per transformer every 2s | — |
| 2 | **ETT Risk Engine** | Physics-informed ensemble anomaly detection | 96% |
| 3 | **DGA Classifier + Quantum VQC** | Multi-method fault classification with quantum validation | 99% |
| 4 | **CAD + Perplexity Sonar** | 3D visualization and web-grounded failure research | — |

**ETT Risk Engine** — Gradient-boosted ensemble (XGBoost, LightGBM, CatBoost, Random Forest) with 36 engineered features including thermal stress, Arrhenius aging factor, and joule heating proxy. Triggers DGA analysis when risk exceeds 50%.

**DGA Fault Classifier** — Consensus between Rogers Ratios (IEEE C57.104), Duval Triangle, and a trained ensemble. Classifies faults as Normal, Thermal, Discharge, or Arcing.

**Quantum VQC** — 6-qubit variational quantum circuit with 4 layers and 72 trainable parameters. Provides an independent validation signal through a fundamentally different computational paradigm. 3-way majority vote with Rogers and Duval methods.

**Perplexity Sonar** — Web-grounded research that finds real, documented transformer failures matching the detected fault pattern. Identifies the most likely failing physical component and highlights it on the 3D CAD model.

## API

| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/chat` | Local chat via Nemotron 4B |
| POST | `/api/search` | Web-grounded research via Perplexity Sonar |
| POST | `/api/predict` | Quantum VQC fault prediction |
| GET | `/api/fleet/metrics` | Fleet-wide health metrics |
| GET | `/api/nvidia/status` | Hardware and model status |
| WS | `/ws/telemetry` | Live sensor stream (2s interval) |

Full API documentation available at `http://localhost:8000/docs`.

## Hardware

| Tier | Device | Role |
|------|--------|------|
| Cloud | DGX Spark (128GB) | Training and ensemble optimization |
| Edge | RTX 5090 (32GB GDDR7) | Inference, cuQuantum simulation, Ollama serving |
| Field | Jetson Orin Nano Super (67 TOPS, 25W) | Substation deployment, zero cloud dependency |

## Responsible AI

- **Transparency** — All intermediate calculations (features, ratios, agreement scores, class probabilities) are exposed in every API response
- **Consensus** — No single model controls output; 3-way majority voting with automatic confidence penalties for disagreement
- **Fairness** — Physics-based deterministic scoring with identical thresholds across all transformers; no demographic data
- **Safety** — Tiered activation (ETT continuous, DGA at 50% risk, VQC alongside DGA); human-in-the-loop for all actions
- **Privacy** — All inference runs locally on NVIDIA hardware; sensor data never leaves the network


## Detected evidence (automated analysis)

Indexed codebase: 34 recognized source files, 521 KB.
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- HTML (language) — detected in the code
- JavaScript (language) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- Node.js (technology) — claimed on Devpost, not found in the code
- Vercel (technology) — claimed on Devpost, not found in the code

## Codebase structure (from repository index)

### Files (41 of 41)

```
.gitignore
archive/cerebras_predictor.py
archive/ChatPanel.jsx
archive/GridLoadChart.jsx
archive/gridveda-live.html
archive/liquid_network.py
archive/lstm_autoencoder.py
archive/start.sh
backend/ai_engine/__init__.py
backend/ai_engine/ensemble.py
backend/ai_engine/ETTm1.csv
backend/ai_engine/models/transformer_monitoring.pkl
backend/ai_engine/nemotron_chat.py
backend/ai_engine/perplexity_chat.py
backend/ai_engine/quantum_vqc.py
backend/ai_engine/transformer_dga_data.csv
backend/main.py
backend/requirements.txt
frontend/index.html
frontend/package.json
frontend/src/App.jsx
frontend/src/components/ChatBubble.jsx
frontend/src/components/ChatOverlay.jsx
frontend/src/components/ComponentsSidebar.jsx
frontend/src/components/Dashboard.jsx
frontend/src/components/DGAGraph.jsx
frontend/src/components/NvidiaPanel.jsx
frontend/src/components/PerplexityPanel.jsx
frontend/src/components/SpecsPanel.jsx
frontend/src/components/TempLoadGraph.jsx
frontend/src/components/TransformerCanvas.jsx
frontend/src/components/TransformerDetail.jsx
frontend/src/components/VariablesGrid.jsx
frontend/src/main.jsx
frontend/src/styles/App.css
frontend/src/utils/componentKeyMap.js
frontend/src/utils/transformerModel.js
frontend/vite.config.js
README.md
start-mac.sh
start.bat
```

### Dependencies

- backend/requirements.txt: catboost@>=1.2.0, fastapi@>=0.109.0, httpx@>=0.27.0, joblib@>=1.3.0, lightgbm@>=4.0.0, numpy@>=1.26.0, pandas@>=2.0.0, pydantic@>=2.6.0, python-dotenv@>=1.0.0, scikit-learn@>=1.3.0, scipy@>=1.11.0, uvicorn@>=0.27.0, websockets@>=12.0, xgboost@>=2.0.0
- frontend/package.json: @vitejs/plugin-react@^4.2.0, lucide-react@^0.564.0, react@^18.2.0, react-dom@^18.2.0, react-markdown@^10.1.0, remark-gfm@^4.0.1, three@^0.182.0, vite@^5.4.0

### Recent commits (newest first)

- Clean up codebase: remove unused models/features and improve CAD integration
- add real-time graph components ported from gridveda-live.html
- wire all endpoints to real test data and live telemetry snapshot
- wire chat and fleet endpoints to live telemetry snapshot
- fix start-mac.sh Python detection to prefer Anaconda over Homebrew
- add markdown chat rendering, full fleet context, and Ollama Nemotron routing
- fix model deserialization for cross-environment pickle loading
- optimize start-mac.sh for Apple Silicon M4 Pro
- add macOS development startup script
- update frontend to display ETT/DGA/Quantum analysis results
- add pre-trained ensemble models, real datasets, and ETT/DGA prediction
- add floating Nemotron chat bubble with voice input
- Revert "add floating chat bubble with Perplexity AI and voice input"
- add floating chat bubble with Perplexity AI and voice input
- fix batch script nested-if parsing errors on Windows
- integrate React frontend into startup scripts with fallback to standalone HTML
- add Vite build infrastructure for React frontend
- switch primary chat engine from Nemotron to Perplexity Sonar
- add standalone demo dashboard, startup scripts, and documentation
- add React frontend with dashboard, chat panel, and NVIDIA stack view

## Key source files (fetched from GitHub, selected and truncated for size)

### backend/requirements.txt

```
fastapi>=0.109.0
uvicorn>=0.27.0
httpx>=0.27.0
numpy>=1.26.0
pydantic>=2.6.0
websockets>=12.0
python-dotenv>=1.0.0
pandas>=2.0.0
scikit-learn>=1.3.0
xgboost>=2.0.0
lightgbm>=4.0.0
catboost>=1.2.0
scipy>=1.11.0
joblib>=1.3.0

```

### frontend/package.json

```
{
  "name": "gridveda-frontend",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "lucide-react": "^0.564.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-markdown": "^10.1.0",
    "remark-gfm": "^4.0.1",
    "three": "^0.182.0"
  },
  "devDependencies": {
    "@vitejs/plugin-react": "^4.2.0",
    "vite": "^5.4.0"
  }
}

```

### frontend/src/main.jsx

```javascript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './styles/App.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

```

### frontend/src/App.jsx

```javascript
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Zap, LayoutDashboard, Cpu, RefreshCw } from 'lucide-react';
import Dashboard from './components/Dashboard';
import NvidiaPanel from './components/NvidiaPanel';
import TransformerDetail from './components/TransformerDetail';
import ChatBubble from './components/ChatBubble';
import './styles/App.css';

const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:8000';
const WS_URL = import.meta.env.VITE_WS_URL || 'ws://localhost:8000/ws/telemetry';

const MAX_HISTORY = 200; // Keep last N telemetry ticks for graphs

function App() {
  const [activeTab, setActiveTab] = useState('dashboard');
  const [telemetry, setTelemetry] = useState(null);
  const [alerts, setAlerts] = useState([]);
  const [connected, setConnected] = useState(false);
  const [selectedTransformer, setSelectedTransformer] = useState(null);
  const [nvidiaStatus, setNvidiaStatus] = useState(null);
  const [telemetryHistory, setTelemetryHistory] = useState([]);
  const [transformerHistory, setTransformerHistory] = useState({});
  const wsRef = useRef(null);
  const reconnectRef = useRef(null);

  // WebSocket connection with auto-reconnect
  const connectWS = useCallback(() => {
    if (wsRef.current?.readyState === WebSocket.OPEN) return;

    const ws = new WebSocket(WS_URL);
    wsRef.current = ws;

    ws.onopen = () => {
      setConnected(true);
      console.log('WebSocket connected to GridVeda');
    };

    ws.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.type === 'telemetry') {
        setTelemetry(data);

        // Accumulate fleet-level history for dashboard charts
        setTelemetryHistory(prev => [...prev, data].slice(-MAX_HISTORY));

        // Accumulate per-transformer reading history for detail graphs
        if (data.readings) {
          setTransformerHistory(prev => {
            const next = { ...prev };
            for (const [id, reading] of Object.entries(data.readings)) {
              if (!next[id]) next[id] = [];
              next[id] = [...next[id], reading].slice(-MAX_HISTORY);
            }
            return next;
          });
        }

        if (data.alerts?.length > 0) {
          setAlerts(prev => [...data.alerts, ...prev].slice(0, 50));
        }
      }
    };

    ws.onclose = () => {
      setConnected(false);
      reconnectRef.current = setTimeout(connectWS, 3000);
    };

    ws.onerror = () => ws.close();
  }, []);

  useEffect(() => {
    connectWS();
    // Fetch NVIDIA status
    fetch(`${API_BASE}/api/nvidia/status`)
      .then(r => r.json())
      .then(setNvidiaStatus)
      .catch(() => {});

    return () => {
      wsRef.current?.close();
      clearTimeout(reconnectRef.current);
    };
  }, [connectWS]);

  const handleReshuffle = async () => {
    try {
      const res = await fetch(`${API_BASE}/api/telemetry/reshuffle`, { method: 'POST' });
      const data = await res.json();
      console.log('Reshuffle:', data);
      // Clear all state so dashboard fully resets
      setTelemetry(null);
      setTelemetryHistory([]);
      setTransformerHistory({});
      setAlerts([]);
    } catch (err) {
      console.error('Reshuffle failed:', err);
    }
  };

  const tabs = [
    { id: 'dashboard', label: 'Dashboard', icon: <LayoutDashboard size={16} strokeWidth={1.5} /> },
    { id: 'nvidia', label: 'Responsible AI', icon: <Cpu size={16} strokeWidth={1.5} /> },
  ];

  return (
    <div className="app">
      {/* Top Navigation */}
      <nav className="top-nav">
        <div className="nav-brand">
          <Zap size={18} strokeWidth={1.5} className="brand-icon" />
          <span className="brand-text">GridVeda</span>
        </div>

        <div className="nav-tabs" data-active={activeTab === 'nvidia' ? '1' : '0'}>
          {tabs.map(tab => (
            <button
              key={tab.id}
              className={`nav-tab ${activeTab === tab.id ? 'active' : ''}`}
              onClick={() => { setActiveTab(tab.id); setSelectedTransformer(null); }}
            >
              <span className="tab-icon">{tab.icon}</span>
              {tab.label}
            </button>
          ))}
        </div>

        <div className="nav-status">
          <button
            className="reshuffle-btn"
            onClick={handleReshuffle}
            disabled={!connected}
            title="Pick new random starting points in test data"
          >
            <RefreshCw size={14} strokeWidth={2} />
            Reshuffle
          </button>
          <span className={`status-dot ${connected ? 'online' : 'offline'}`} />
          <span className="status-text">
            {connected ? 'Live' : 'Reconnecting...'}
          </span>
          {telemetry && (
            <span className="tick-counter">T+{telemetry.tick}</span>
          )}
        </div>
      </nav>

      {/* Main Content */}
      <main className="main-content">
        {selectedTransformer ? (
          <TransformerDetail
            transformerId={selectedTransformer}
            telemetry={telemetry}
            history={transformerHistory[selectedTransformer] || []}
            onBack={() => setSelectedTransformer(null)}
            apiBase={API_BASE}
          />
        ) : (
          <>
            {activeTab === 'dashboard' && (
              <Dashboard
                telemetry={telemetry}
                alerts={alerts}
                telemetryHistory={telemetryHistory}
                transformerHistory={transformerHistory}
                onSelectTransformer={setSelectedTransformer}
              />
            )}
            {activeTab === 'nvidia' && (
              <NvidiaPanel status={nvidiaStatus} telemetry={telemetry} />
            )}
          </>
        )}
      </main>

      {/* Floating Chat Bubble — always visible */}
      <ChatBubble apiBase={API_BASE} telemetry={telemetry} />
    </div>
  );
}

export default App;

```

### start-mac.sh

```shell
#!/usr/bin/env bash
# ════════════════════════════════════════════════════════════════
# GridVeda — macOS Development Script (Apple Silicon)
# Runs the full stack: FastAPI backend + React frontend
# Pre-trained models load via joblib — optimized for Apple Silicon
# ════════════════════════════════════════════════════════════════
set -e

# ─── Colors ───
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
RED='\033[0;31m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

clear
echo ""
echo -e "${CYAN}${BOLD}"
echo "   ██████╗ ██████╗ ██╗██████╗ ██╗   ██╗███████╗██████╗  █████╗ "
echo "  ██╔════╝ ██╔══██╗██║██╔══██╗██║   ██║██╔════╝██╔══██╗██╔══██╗"
echo "  ██║  ███╗██████╔╝██║██║  ██║██║   ██║█████╗  ██║  ██║███████║"
echo "  ██║   ██║██╔══██╗██║██║  ██║╚██╗ ██╔╝██╔══╝  ██║  ██║██╔══██║"
echo "  ╚██████╔╝██║  ██║██║██████╔╝ ╚████╔╝ ███████╗██████╔╝██║  ██║"
echo "   ╚═════╝ ╚═╝  ╚═╝╚═╝╚═════╝   ╚═══╝  ╚══════╝╚═════╝ ╚═╝  ╚═╝"
echo -e "${NC}"
echo -e "${BOLD}  AI Grid Intelligence${NC}"
echo -e "${DIM}  Apple Silicon Edition${NC}"
echo -e "${CYAN}  ════════════════════════════════════════════════════════${NC}"
echo ""

# ════════════════════════════════════════
# STEP 1: APPLE SILICON DETECTION + PYTHON
# ════════════════════════════════════════
echo -e "${YELLOW}[1/5] Detecting Apple Silicon + Python...${NC}"
cd "${SCRIPT_DIR}/backend"

# ─── Detect Apple Silicon chip ───
ARCH=$(uname -m)
CHIP_NAME="Unknown"
CHIP_CORES=""
PERF_CORES=""
EFF_CORES=""
GPU_CORES=""
NEURAL_ENGINE=""
RAM_GB=""

if [ "$ARCH" = "arm64" ]; then
    CHIP_NAME=$(sysctl -n machdep.cpu.brand_string 2>/dev/null || echo "Apple Silicon")

    TOTAL_CORES=$(sysctl -n hw.ncpu 2>/dev/null || echo "?")
    PERF_CORES=$(sysctl -n hw.perflevel0.logicalcpu 2>/dev/null || echo "?")
    EFF_CORES=$(sysctl -n hw.perflevel1.logicalcpu 2>/dev/null || echo "?")

    GPU_CORES=$(system_profiler SPDisplaysDataType 2>/dev/null | grep "Total Number of Cores" | awk -F': ' '{print $2}' | head -1)
    [ -z "$GPU_CORES" ] && GPU_CORES="?"

    NEURAL_ENGINE="16-core"

    RAM_BYTES=$(sysctl -n hw.memsize 2>/dev/null || echo "0")
    RAM_GB=$((RAM_BYTES / 1073741824))

    echo -e "${GREEN}   + ${CHIP_NAME}${NC}"
    echo -e "${GREEN}     ${PERF_CORES}P + ${EFF_CORES}E CPU cores / ${GPU_CORES}-core GPU / ${NEURAL_ENGINE} Neural Engine${NC}"
    echo -e "${GREEN}     ${RAM_GB} GB unified memory${NC}"

    # Apple Accelerate Framework optimization
    export VECLIB_MAXIMUM_THREADS="${TOTAL_CORES}"
    export OMP_NUM_THREADS="${PERF_CORES}"
    export OPENBLAS_NUM_THREADS="${PERF_CORES}"
    echo -e "${GREEN}   + Accelerate framework — ${PERF_CORES} performance threads${NC}"
else
    echo -e "${YELLOW}   ! Intel Mac detected (${ARCH}) — no Apple Silicon acceleration${NC}"
fi

# ─── Python ───
# Prefer Anaconda/Miniconda Python (has ML packages pre-installed and writable pip)
# over Homebrew Python 3.14 (externally-managed, blocks pip install)
PYTHON_CMD=""
for candidate in \
    "$HOME/anaconda3/bin/python3" \
    "$HOME/miniconda3/bin/python3" \
    "$HOME/miniforge3/bin/python3" \
    "/opt/anaconda3/bin/python3" \
    "$(command -v python3 2>/dev/null)" \
    "$(command -v python 2>/dev/null)"; do
    if [ -n "$candidate" ] && [ -x "$candidate" ]; then
        if "$candidate" -m pip --version > /dev/null 2>&1; then
            PYTHON_CMD="$candidate"
            break
        fi
    fi
done

if [ -z "$PYTHON_CMD" ]; then
    echo -e "${RED}   x No usable Python found — install Anaconda or Miniconda${NC}"
    echo -e "${RED}     Homebrew Python blocks pip install (PEP 668)${NC}"
    echo -e "${RED}     https://www.anaconda.com/download${NC}"
    exit 1
fi

PYTHON_VER=$($PYTHON_CMD --version 2>&1)
echo -e "${GREEN}   + ${PYTHON_VER} ($(dirname "$PYTHON_CMD"))${NC}"

$PYTHON_CMD -m pip install -r requirements.txt --quiet --disable-pip-version-check 2>/dev/null || {
    echo -e "${YELLOW}   ! pip install failed — trying with --user flag...${NC}"
    $PYTHON_CMD -m pip install -r requirements.txt --quiet --user 2>/dev/null || true
}
echo -e "${GREEN}   + Python packages installed${NC}"
echo -e "${DIM}     (pandas, scikit-learn, xgboost, lightgbm, catboost, fastapi, etc.)${NC}"

# ════════════════════════════════════════
# STEP 2: OLLAMA & NEMOTRON NANO 4B
# ════════════════════════════════════════
echo -e "\n${YELLOW}[2/5] Setting up Ollama + Nemotron Nano 4B (optional)...${NC}"

OLLAMA_READY=false

if command -v ollama &> /dev/null; then
    OLLAMA_VER=$(ollama --version 2>/dev/null || echo "installed")
    echo -e "${GREEN}   + Ollama found: ${OLLAMA_VER}${NC}"

    if curl -sf http://localhost:11434/api/tags > /dev/null 2>&1; then
        echo -e "${GREEN}   + Ollama server already running${NC}"
    else
        echo -e "${YELLOW}   Starting Ollama server...${NC}"
        ollama serve > /tmp/ollama-gridveda.log 2>&1 &
        OLLAMA_PID=$!

        for i in {1..15}; do
            if curl -sf http://localhost:11434/api/tags > /dev/null 2>&1; then
                echo -e "${GREEN}   + Ollama server started${NC}"
                break
            fi
            sleep 1
        done

        if ! curl -sf http://localhost:11434/api/tags > /dev/null 2>&1; then
            echo -e "${RED}   x Ollama server failed to start — check /tmp/ollama-gridveda.log${NC}"
        fi
    fi

    if ollama list 2>/dev/null | grep -qi "nemotron"; then
        echo -e "${GREEN}   + Nemotron Nano 4B available${NC}"
        OLLAMA_READY=true
    else
        echo -e "${YELLOW}   Nemotron not found. Pull it for local AI chat:${NC}"
        echo ""
        read -p "   Pull nemotron-nano-4b-instruct (~2.5GB)? (Y/n): " pull_choice
        pull_choice=${pull_choice:-Y}
        if [[ "$pull_choice" =~ ^[Yy]$ ]]; then
            ollama pull nemotron-nano-4b-instruct
            echo -e "${GREEN}   + Nemotron Nano 4B pulled — local inference ready${NC}"
            OLLAMA_READY=true
        else
            echo -e "${YELLOW}   ! 
[truncated — 6700 more characters]
```

### frontend/vite.config.js

```javascript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  server: {
    port: 5173,
    proxy: {
      '/api': {
        target: 'http://localhost:8000',
        changeOrigin: true,
      },
      '/ws': {
        target: 'ws://localhost:8000',
        ws: true,
      },
    },
  },
})

```

### frontend/index.html

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>GridVeda — AI Grid Intelligence</title>
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='32' height='32' viewBox='0 0 24 24' fill='none' stroke='%230cc0a0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><polygon points='13 2 3 14 12 14 11 22 21 10 12 10 13 2'/></svg>" />
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

```

### archive/GridLoadChart.jsx

```javascript
import React, { useMemo } from 'react';

/**
 * Animated bar chart showing live grid load history.
 * Alternating NVIDIA green / cyan bars.
 * Ported from gridveda-live.html renderChart().
 */
function GridLoadChart({ telemetryHistory, maxBars = 24 }) {
  const bars = useMemo(() => {
    if (!telemetryHistory || telemetryHistory.length === 0) {
      return Array(maxBars).fill(50);
    }
    // Use the last N ticks' average load
    return telemetryHistory.slice(-maxBars).map(t => {
      if (t?.fleet_metrics?.avg_load != null) return t.fleet_metrics.avg_load;
      // Fallback: compute from readings
      const readings = Object.values(t?.readings || {});
      if (readings.length === 0) return 50;
      return readings.reduce((sum, r) => sum + (r.load_percent || 0), 0) / readings.length;
    });
  }, [telemetryHistory, maxBars]);

  return (
    <div className="load-chart-box">
      <div className="load-chart-title">Live Grid Load — Last {bars.length} Ticks</div>
      <div className="load-chart-bars">
        {bars.map((val, i) => (
          <div
            key={i}
            className={`load-bar ${i % 2 === 0 ? 'even' : 'odd'}`}
            style={{ height: `${Math.max(5, val)}%` }}
          />
        ))}
      </div>
    </div>
  );
}

export default GridLoadChart;

```

### archive/ChatPanel.jsx

```javascript
import React, { useState, useRef, useEffect } from 'react';
import { Bot, Zap, User, Loader2, ArrowUp } from 'lucide-react';

function ChatPanel({ apiBase, telemetry }) {
  const [messages, setMessages] = useState([
    {
      role: 'assistant',
      content: '**GridVeda AI** — Nemotron Nano 4B (Ollama)\n\nI\'m your grid intelligence assistant. Ask me about:\n- Fleet health status and transformer monitoring\n- DGA analysis and fault classification\n- Alerts, predictions, and maintenance recommendations',
      timestamp: new Date().toISOString(),
    },
  ]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const messagesEndRef = useRef(null);
  const inputRef = useRef(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(scrollToBottom, [messages]);

  const sendMessage = async () => {
    if (!input.trim() || loading) return;

    const userMsg = {
      role: 'user',
      content: input.trim(),
      timestamp: new Date().toISOString(),
    };

    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setLoading(true);

    try {
      const resp = await fetch(`${apiBase}/api/chat`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: userMsg.content,
          context: telemetry ? JSON.stringify(telemetry.fleet_metrics) : null,
        }),
      });

      if (resp.ok) {
        const data = await resp.json();
        setMessages(prev => [...prev, {
          role: 'assistant',
          content: data.response,
          model: data.model,
          engine: data.engine,
          timestamp: new Date().toISOString(),
        }]);
      } else {
        setMessages(prev => [...prev, {
          role: 'assistant',
          content: 'Error communicating with GridVeda backend. Ensure the server is running on port 8000.',
          timestamp: new Date().toISOString(),
          isError: true,
        }]);
      }
    } catch (err) {
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: `Connection failed: ${err.message}\n\nStart the backend:\n\`\`\`\ncd backend && uvicorn main:app --host 0.0.0.0 --port 8000\n\`\`\``,
        timestamp: new Date().toISOString(),
        isError: true,
      }]);
    } finally {
      setLoading(false);
      inputRef.current?.focus();
    }
  };

  const quickActions = [
    { label: 'Fleet Status', msg: 'What is the current fleet health status?' },
    { label: 'DGA Analysis', msg: 'Explain the current DGA readings and any concerns' },
    { label: 'Active Alerts', msg: 'What are the current active alerts and recommendations?' },
    { label: 'Predictions', msg: 'What are the predictive maintenance forecasts?' },
  ];

  return (
    <div className="chat-panel">
      <div className="chat-header">
        <div className="chat-title">
          <span className="chat-icon"><Bot size={24} strokeWidth={1.5} /></span>
          <div>
            <h3>Ask Grid — Nemotron Nano 4B</h3>
            <span className="chat-subtitle">
              100% Local • Ollama • Grid-Aware RAG
            </span>
          </div>
        </div>
        <div className="model-badge">
          <span className="nvidia-dot" />
          Nemotron Nano 4B
        </div>
      </div>

      {/* Quick Actions */}
      <div className="quick-actions">
        {quickActions.map((qa, i) => (
          <button
            key={i}
            className="quick-btn"
            onClick={() => { setInput(qa.msg); }}
            disabled={loading}
          >
            {qa.label}
          </button>
        ))}
      </div>

      {/* Messages */}
      <div className="chat-messages">
        {messages.map((msg, i) => (
          <div key={i} className={`chat-msg ${msg.role} ${msg.isError ? 'error' : ''}`}>
            <div className="msg-avatar">
              {msg.role === 'user' ? <User size={16} strokeWidth={1.5} /> : <Zap size={16} strokeWidth={1.5} />}
            </div>
            <div className="msg-content">
              <div className="msg-text">
                {msg.content.split('\n').map((line, j) => (
                  <React.Fragment key={j}>
                    {line.startsWith('```') ? (
                      <code className="code-block">{line.replace(/```\w*/g, '')}</code>
                    ) : (
                      <span dangerouslySetInnerHTML={{
                        __html: line
                          .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                          .replace(/`(.*?)`/g, '<code>$1</code>')
                      }} />
                    )}
                    <br />
                  </React.Fragment>
                ))}
              </div>
              <div className="msg-meta">
                <span className="msg-time">
                  {new Date(msg.timestamp).toLocaleTimeString()}
                </span>
                {msg.model && (
                  <span className="msg-model">
                    via {msg.model} ({msg.engine})
                  </span>
                )}
              </div>
            </div>
          </div>
        ))}
        {loading && (
          <div className="chat-msg assistant">
            <div className="msg-avatar"><Zap size={16} strokeWidth={1.5} /></div>
            <div className="msg-content">
              <div className="typing-indicator">
                <span /><span /><span />
              </div>
            </div>
          </div>
        )}
        <div ref={messagesEndRef} />
      </div>

      {/* Input */}
      <div className="chat-input-area">
        <input
          ref={inputRef}
          type="text"
          className="chat-input"
          placeholder="Ask about grid health, DGA, alerts, predictions..."
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => e.key === 'Enter' && sendMessage
[truncated — 376 more characters]
```

### archive/liquid_network.py

```python
"""
Liquid Time-Constant (LTC) Network for Grid Time-Series Prediction
Based on Liquid AI's continuous-time neural ODE architecture.
Adapted for real-time transformer health trend forecasting.

Key Properties:
  - Continuous-time dynamics (adaptive time constants)
  - Compact model size (~12K params) suitable for edge deployment
  - Captures long-range temporal dependencies
  - Natural handling of irregular time intervals

Reference: Hasani et al., "Liquid Time-constant Networks" (2021)
"""

import numpy as np
from typing import Dict, Any, Optional


class LiquidTimeConstantNetwork:
    """
    Liquid Time-Constant Network for time-series trend prediction.
    Pure NumPy implementation optimized for Jetson Orin Nano Super deployment.
    """

    def __init__(
        self,
        input_size: int = 9,
        hidden_size: int = 64,
        output_size: int = 3,
        n_ode_steps: int = 6,
        dt: float = 0.1,
        seed: int = 42,
    ):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.n_ode_steps = n_ode_steps
        self.dt = dt
        self.rng = np.random.RandomState(seed)

        # Initialize network parameters
        self._init_params()

        # Trend thresholds
        self.degradation_threshold = 0.65
        self.critical_threshold = 0.85

    def _init_params(self):
        """Initialize LTC network weights with Xavier initialization."""
        def xavier(fan_in, fan_out):
            scale = np.sqrt(2.0 / (fan_in + fan_out))
            return self.rng.randn(fan_in, fan_out) * scale

        # Input projection
        self.W_in = xavier(self.input_size, self.hidden_size)
        self.b_in = np.zeros(self.hidden_size)

        # LTC cell parameters
        # Time constants (learnable, positive via softplus)
        self.tau_raw = self.rng.randn(self.hidden_size) * 0.5 + 1.0

        # Synaptic weights
        self.W_rec = xavier(self.hidden_size, self.hidden_size)
        self.b_rec = np.zeros(self.hidden_size)

        # Input-dependent modulation
        self.W_gate = xavier(self.hidden_size, self.hidden_size)
        self.b_gate = np.zeros(self.hidden_size)

        # Sensitivity kernel
        self.A = xavier(self.hidden_size, self.hidden_size) * 0.1

        # Output projection
        self.W_out = xavier(self.hidden_size, self.output_size)
        self.b_out = np.zeros(self.output_size)

        # Layer norm parameters
        self.ln_gamma = np.ones(self.hidden_size)
        self.ln_beta = np.zeros(self.hidden_size)

    @staticmethod
    def _softplus(x: np.ndarray) -> np.ndarray:
        """Softplus activation: log(1 + exp(x))."""
        return np.where(x > 20, x, np.log1p(np.exp(np.clip(x, -20, 20))))

    @staticmethod
    def _sigmoid(x: np.ndarray) -> np.ndarray:
        """Numerically stable sigmoid."""
        return np.where(
            x >= 0,
            1 / (1 + np.exp(-x)),
            np.exp(x) / (1 + np.exp(x))
        )

    @staticmethod
    def _layer_norm(x: np.ndarray, gamma: np.ndarray, beta: np.ndarray, eps: float = 1e-5) -> np.ndarray:
        """Layer normalization."""
        mean = np.mean(x, axis=-1, keepdims=True)
        var = np.var(x, axis=-1, keepdims=True)
        return gamma * (x - mean) / np.sqrt(var + eps) + beta

    def _ltc_ode_step(self, h: np.ndarray, x_proj: np.ndarray) -> np.ndarray:
        """
        Single LTC ODE integration step:
          dh/dt = (-h + f(h, x)) / τ(x)

        Where:
          f(h, x) = tanh(W_rec @ h + x_proj + b_rec)
          τ(x) = softplus(τ_raw + gate(x))
          gate(x) = sigmoid(W_gate @ x_proj + b_gate)
        """
        # Compute firing rate
        pre_activation = self.W_rec @ h + x_proj + self.b_rec
        f_h = np.tanh(pre_activation)

        # Input-dependent time constant modulation
        gate = self._sigmoid(self.W_gate @ x_proj + self.b_gate)
        tau = self._softplus(self.tau_raw + gate * 2.0)

        # Sensitivity modulation
        sens = np.tanh(self.A @ h) * 0.1

        # ODE: dh/dt = (-h + f(h,x) + sens) / τ
        dh = (-h + f_h + sens) / tau

        # Euler integration
        h_new = h + self.dt * dh
        return h_new

    def _forward_step(self, h: np.ndarray, x: np.ndarray) -> np.ndarray:
        """Process one timestep through LTC cell with sub-stepping."""
        # Project input
        x_proj = x @ self.W_in + self.b_in

        # Sub-step ODE integration for stability
        for _ in range(self.n_ode_steps):
            h = self._ltc_ode_step(h, x_proj)

        # Layer normalization for stability
        h = self._layer_norm(h, self.ln_gamma, self.ln_beta)

        return h

    def _forward_sequence(self, sequence: np.ndarray) -> tuple:
        """
        Process full sequence through LTC network.

        Args:
            sequence: Shape (seq_len, input_size) - normalized sensor readings

        Returns:
            (final_hidden, all_hiddens) - final state and trajectory
        """
        seq_len = sequence.shape[0]
        h = np.zeros(self.hidden_size)
        hiddens = []

        for t in range(seq_len):
            h = self._forward_step(h, sequence[t])
            hiddens.append(h.copy())

        return h, np.array(hiddens)

    def predict(self, sequence: np.ndarray) -> Dict[str, Any]:
        """
        Predict transformer health trend from time-series data.

        Args:
            sequence: Shape (seq_len, 9) normalized sensor data
                      [temp, load, h2, ch4, c2h2, c2h4, c2h6, moisture, vibration]

        Returns:
            Dict with trend, predicted_hours, severity, trajectory
        """
        if sequence.ndim == 1:
            sequence = sequence.reshape(1, -1)

        # Forward pass
        h_final, h_trajectory = self._forward_sequence(sequence)

        # Output projection → [risk, rate_of_change, time_to_threshold]
        output = h_final @ self.W_out + self.b_out
        risk = float(self._sigmoid(np.arra
[truncated — 2563 more characters]
```

[21 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]