mohammademad2003 commited on
Commit
999b2e2
·
1 Parent(s): 124f6bd
Files changed (2) hide show
  1. README.md +913 -5
  2. requirements.txt +27 -0
README.md CHANGED
@@ -1,10 +1,918 @@
1
  ---
2
- title: Optiq
3
- emoji: 📚
4
- colorFrom: pink
5
- colorTo: purple
6
  sdk: docker
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: OptiQ
3
+ emoji:
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: docker
7
  pinned: false
8
  ---
9
 
10
+ <p align="center">
11
+ <img src="https://img.shields.io/badge/Python-3.12-blue?style=flat-square&logo=python" />
12
+ <img src="https://img.shields.io/badge/Qiskit-2.3-6929C4?style=flat-square&logo=ibm" />
13
+ <img src="https://img.shields.io/badge/PyTorch-2.9-EE4C2C?style=flat-square&logo=pytorch" />
14
+ <img src="https://img.shields.io/badge/FastAPI-0.128-009688?style=flat-square&logo=fastapi" />
15
+ <img src="https://img.shields.io/badge/React-18-61DAFB?style=flat-square&logo=react" />
16
+ <img src="https://img.shields.io/badge/License-MIT-green?style=flat-square" />
17
+ </p>
18
+
19
+ # ⚡ OptiQ — Hybrid Quantum-AI-Classical Grid Optimization Platform
20
+
21
+ > **AI-Powered Distribution Grid Reconfiguration SaaS.**
22
+ > Reduces grid losses by **31 %+** through intelligent network reconfiguration using a three-stage hybrid pipeline: **Quantum Topology Search → GNN Warm-Start → Classical AC-Power-Flow Verification.**
23
+
24
+ **The first working prototype of the hybrid Quantum-AI-Classical optimization stack for power distribution networks** — a software-only solution that works on existing infrastructure with zero hardware changes.
25
+
26
+ ---
27
+
28
+ ## Table of Contents
29
+
30
+ 1. [Overview](#overview)
31
+ 2. [Results](#results)
32
+ 3. [Architecture](#architecture)
33
+ 4. [Hybrid Pipeline — How It Works](#hybrid-pipeline--how-it-works)
34
+ 5. [Mathematical Foundations](#mathematical-foundations)
35
+ 6. [Project Structure](#project-structure)
36
+ 7. [Backend API Endpoints](#backend-api-endpoints)
37
+ 8. [Frontend Pages](#frontend-pages)
38
+ 9. [Database Schema](#database-schema)
39
+ 10. [Authentication](#authentication)
40
+ 11. [Grid Visualization & Out-of-Service Lines](#grid-visualization--out-of-service-lines)
41
+ 12. [Evaluation & Impact Metrics](#evaluation--impact-metrics)
42
+ 13. [Egypt-Specific Scaling & Implementation](#egypt-specific-scaling--implementation)
43
+ 14. [Configuration](#configuration)
44
+ 15. [Installation](#installation)
45
+ 16. [Running the Application](#running-the-application)
46
+ 17. [Deployment with ngrok](#deployment-with-ngrok)
47
+ 18. [Environment Variables](#environment-variables)
48
+ 19. [Tech Stack](#tech-stack)
49
+ 20. [References](#references)
50
+
51
+ ---
52
+
53
+ ## Overview
54
+
55
+ Electric power distribution grids lose **5–13 %** of generated energy as resistive (I²R) losses in feeder cables. **Network reconfiguration** — opening / closing sectionalising and tie switches — can dramatically reduce these losses while maintaining supply to every bus.
56
+
57
+ OptiQ solves this NP-hard combinatorial problem with a **hybrid pipeline** that chains:
58
+
59
+ | Stage | Engine | Role |
60
+ |-------|--------|------|
61
+ | **1. Quantum / SA Topology Search** | Qiskit QAOA or Simulated Annealing | Explore the exponential configuration space, produce top-K candidate topologies |
62
+ | **2. AI Warm-Start** | 3-layer GraphSAGE GNN | Predict bus voltages instantly for each candidate (avoids expensive Newton–Raphson per candidate) |
63
+ | **3. Classical Verification** | pandapower Newton–Raphson AC-OPF | Verify the best candidate(s) with full AC power flow for engineering-grade accuracy |
64
+
65
+ The platform includes a **full SaaS frontend** (React + Vite + Tailwind CSS) with interactive grid visualization (React Flow), real-time optimization, ROI calculator, PDF reports, audit logs, and a digital-twin scenario simulator.
66
+
67
+ ---
68
+
69
+ ## Results
70
+
71
+ ### OptiQ vs Published Algorithms (IEEE 33-Bus)
72
+
73
+ Many metaheuristics get trapped at local optima (~146 kW). OptiQ consistently finds the global optimal. All sources listed in [REFERENCES.md](REFERENCES.md).
74
+
75
+ | Method | Loss (kW) | Reduction | Source |
76
+ |--------|-----------|-----------|--------|
77
+ | Baseline (no reconfiguration) | 202.68 | -- | [1] |
78
+ | Civanlar load-transfer heuristic (1988) | ~146 | ~28% | [2] |
79
+ | PSO (Sulaima 2014, local optimum) | 146.1 | 27.9% | [5] |
80
+ | Baran & Wu branch exchange (1989) | 139.55 | 31.15% | [1] |
81
+ | Goswami & Basu heuristic (1992) | 139.55 | 31.15% | [3] |
82
+ | GA (well-tuned, multiple authors) | 139.55 | 31.15% | [7] |
83
+ | MILP exact (Jabr 2012) | 139.55 | 31.15% | [4] |
84
+ | Branch Exchange + Clustering (Pereira 2023) | 139.55 | 31.15% | [6] |
85
+ | **OptiQ Classical** | **139.55** | **31.15%** | this work |
86
+ | **OptiQ Quantum SA** | **139.55** | **31.15%** | this work |
87
+ | **OptiQ Hybrid** | **139.55** | **31.15%** | this work |
88
+
89
+ ### OptiQ vs Industry Practice
90
+
91
+ | Solution | Loss Reduction | Cost | Limitation |
92
+ |----------|---------------|------|-----------|
93
+ | Manual switching (status quo in Egypt) | 5-10% [9] | $0 software | Cannot adapt to load changes. Human error. Slow. |
94
+ | Basic ADMS module (ABB/Siemens/GE) | 15-25% [9][22] | $5-50M [22] | Massive CAPEX. 12-24 month deploy. New hardware. |
95
+ | **OptiQ** | **28-32%** | $200/feeder/month | Software-only. Zero CAPEX. Deploys in weeks. |
96
+
97
+ ### Detailed Results
98
+
99
+ | Method | Loss (kW) | Reduction | Min V (pu) | Violations | Time (s) |
100
+ |--------|-----------|-----------|------------|------------|----------|
101
+ | Baseline (default) | 202.68 | -- | 0.9131 | 21 | -- |
102
+ | **Published Optimal** [1] | **139.55** | **31.15%** | -- | -- | -- |
103
+ | OptiQ Classical | 139.55 | 31.15% | 0.9378 | 7 | 10.7 |
104
+ | OptiQ Quantum SA | 139.55 | 31.15% | 0.9378 | 7 | 17.1 |
105
+ | OptiQ Hybrid | 139.55 | 31.15% | 0.9378 | 7 | 18.1 |
106
+
107
+ ### Multi-Load Robustness
108
+
109
+ | Load Multiplier | Base Loss (kW) | Optimized (kW) | Reduction |
110
+ |-----------------|----------------|----------------|-----------|
111
+ | 0.70x | 94.91 | 66.99 | 29.4% |
112
+ | 0.85x | 143.09 | 102.11 | 28.6% |
113
+ | 1.00x (nominal) | 202.68 | 141.92 | 30.0% |
114
+ | 1.15x | 274.58 | 187.90 | 31.6% |
115
+ | 1.30x | 359.82 | 243.80 | 32.2% |
116
+
117
+ ---
118
+
119
+ ## Architecture
120
+
121
+ ```
122
+ ┌──────────────────────────────────────────────────────────────┐
123
+ │ React SPA (Vite) │
124
+ │ Landing · Dashboard · Grid View · ROI · Audit · Reports │
125
+ └──────────┬───────────────────────────────────────────────────┘
126
+ │ REST / JSON
127
+ ┌──────────▼───────────────────────────────────────────────────┐
128
+ │ FastAPI (uvicorn + ngrok tunnel) │
129
+ │ /api/baseline · /api/optimize · /api/grid · /api/auth ... │
130
+ └──────────┬─────────────┬─────────────┬───────────────────────┘
131
+ │ │ │
132
+ ┌──────▼──────┐ ┌────▼─────┐ ┌────▼──────┐
133
+ │ Quantum / │ │ AI / │ │ Classical │
134
+ │ SA Search │ │ GNN │ │ pandapower│
135
+ │ (Qiskit) │ │ (PyTorch)│ │ (AC PF) │
136
+ └─────────────┘ └──────────┘ └───────────┘
137
+
138
+ ┌─────▼─────┐
139
+ │ SQLite │
140
+ │ optiq.db │
141
+ └───────────┘
142
+ ```
143
+
144
+ **Pipeline flow:**
145
+
146
+ ```
147
+ IEEE Test Data (pandapower built-in)
148
+
149
+ [Quantum: SA on QUBO] ──→ Top-5 candidate topologies
150
+
151
+ [AI: Physics-Informed GNN] ──→ Predicted voltages for each topology
152
+
153
+ [Classical: pandapower AC Power Flow] ──→ Verified feasible solutions
154
+
155
+ Best Solution ──→ FastAPI ──→ Frontend Dashboard
156
+ ```
157
+
158
+ ---
159
+
160
+ ## Hybrid Pipeline — How It Works
161
+
162
+ The core pipeline is implemented in `src/hybrid/pipeline.py → run_hybrid_pipeline()`:
163
+
164
+ ### Stage 1 — Quantum / Simulated Annealing Topology Search
165
+
166
+ **File:** `src/quantum/qaoa_reconfig.py`
167
+
168
+ 1. Build a **QUBO (Quadratic Unconstrained Binary Optimization)** matrix from the network graph.
169
+ 2. Each binary decision variable xᵢ represents a line: `1 = open (out of service)`, `0 = closed`.
170
+ 3. **Simulated Annealing** (primary solver):
171
+ - Proposes swap moves (close one tie line, open one feeder line).
172
+ - Checks radiality (connected tree for distribution networks).
173
+ - Runs quick AC power flow via pandapower.
174
+ - Accepts/rejects via **Metropolis criterion**.
175
+ - Multi-restart: 5 restarts × 500 iterations, cooling rate 0.99.
176
+ 4. Alternatively, a **reduced QAOA** solver (`solve_qaoa_reduced`) can run on ≤15 qubits using Qiskit's `StatevectorSampler` + COBYLA optimizer.
177
+ 5. A **QUBO export** function (`get_qubo_for_qpu`) prepares the matrix for external QPU submission (D-Wave / IBM Quantum).
178
+ 6. Output: **Top-K candidate topologies** ranked by total losses.
179
+
180
+ ### Stage 2 — GNN Warm-Start
181
+
182
+ **File:** `src/ai/model.py`
183
+
184
+ 1. A pre-trained **3-layer GraphSAGE GNN** (`OptiQGNN`) predicts bus voltage magnitudes for each candidate topology.
185
+ 2. Input features per node (5-dim): `[Pd, Qd, Vm_init, is_slack, is_gen]`.
186
+ 3. Input features per edge (3-dim): `[R, X, in_service]`.
187
+ 4. Architecture: 3 × SAGEConv layers with **residual connections**, **LayerNorm**, and **dropout**.
188
+ 5. Output: Per-bus voltage magnitude clamped to [0.90, 1.10] p.u. via sigmoid scaling.
189
+ 6. Training uses a **physics-informed loss** with dynamic Lagrange multipliers (DeepOPF-NGT inspired).
190
+
191
+ ### Stage 3 — Classical AC Power Flow Verification
192
+
193
+ **File:** `src/grid/power_flow.py`
194
+
195
+ 1. The best candidate from Stage 2 is passed to **pandapower's Newton–Raphson AC power flow solver**.
196
+ 2. Extracts full results: total losses (kW), voltage profile, line loadings, voltage violations.
197
+ 3. Returns the verified optimal topology with engineering-grade accuracy.
198
+
199
+ ### Fallback — Classical Branch-Exchange
200
+
201
+ **File:** `src/grid/reconfiguration.py`
202
+
203
+ A heuristic branch-exchange search (`branch_exchange_search`) is used as:
204
+ - Baseline comparator for the hybrid pipeline.
205
+ - Fallback when quantum/AI stages are unavailable.
206
+ - Iteratively swaps open/closed line pairs, keeping swaps that reduce losses, until no improving swap exists.
207
+
208
+ ---
209
+
210
+ ## Mathematical Foundations
211
+
212
+ ### QUBO Formulation
213
+
214
+ The cost Hamiltonian (`src/quantum/hamiltonian.py`) constructs:
215
+
216
+ $$\min_{\mathbf{x}} \; \mathbf{x}^T \mathbf{Q} \, \mathbf{x}$$
217
+
218
+ Where:
219
+ - **Objective (diagonal):** $Q_{ii} = -c_i + P(1 - 2K)$
220
+ - **Coupling (off-diagonal):** $Q_{ij} = P \quad \forall\, i < j$
221
+ - **Loss coefficient:** $c_i = r_i \cdot P_i^2 / V^2$ (per-line approximate resistive loss)
222
+ - **Radiality constraint:** Penalty $P \cdot \left(\sum x_i - K\right)^2$ ensures exactly $K$ lines are open
223
+ - $K = $ number of tie switches (5 for IEEE 33-bus)
224
+
225
+ ### Simulated Annealing — Metropolis Criterion
226
+
227
+ $$P(\text{accept}) = \begin{cases} 1 & \text{if } \Delta E < 0 \\ e^{-\Delta E / T} & \text{otherwise} \end{cases}$$
228
+
229
+ Cooling schedule: $T \leftarrow 0.99 \cdot T$ per iteration.
230
+
231
+ ### GNN Physics-Informed Loss
232
+
233
+ $$\mathcal{L} = \underbrace{\| V_{pred} - V_{true} \|^2}_{\text{MSE}} + \lambda_v \cdot \underbrace{\text{mean}\left[\max(0, v_{min} - V_m)^2 + \max(0, V_m - v_{max})^2\right]}_{\text{Voltage bound violation}}$$
234
+
235
+ With **dynamic Lagrange multiplier** update (dual gradient ascent):
236
+
237
+ $$\lambda_v \leftarrow \max\!\left(0,\; \lambda_v + \eta \cdot \text{violation}\right)$$
238
+
239
+ ### Power Flow (Newton–Raphson)
240
+
241
+ pandapower solves the full AC power flow equations:
242
+
243
+ $$S_i = V_i \sum_{k=1}^{n} Y_{ik}^* V_k^*$$
244
+
245
+ Where $S_i$ is complex power injection, $V_i$ is bus voltage, and $Y_{ik}$ is the bus admittance matrix element. The Newton–Raphson method iteratively solves the non-linear system using the Jacobian matrix.
246
+
247
+ ### Impact Calculations
248
+
249
+ | Metric | Formula |
250
+ |--------|---------|
251
+ | **Loss reduction (kW)** | $\Delta P = P_{baseline} - P_{optimized}$ |
252
+ | **Loss reduction (%)** | $100 \times \Delta P / P_{baseline}$ |
253
+ | **Annual energy saved (MWh/yr)** | $\Delta P \times 8760 / 1000$ |
254
+ | **CO₂ saved (tonnes/yr)** | $\text{Energy saved (kWh)} \times \epsilon_f / 1000$ |
255
+ | **Cost saved (USD/yr)** | $\text{Energy saved (kWh)} \times \text{price}_{\$/kWh}$ |
256
+
257
+ Where $\epsilon_f = 0.475$ kg CO₂/kWh (global grid average) and price = $0.10/kWh.
258
+
259
+ ---
260
+
261
+ ## Project Structure
262
+
263
+ ```
264
+ OptiQ/
265
+ ├── api/ # FastAPI backend
266
+ │ ├── main.py # Entry point, router registration, ngrok startup
267
+ │ ├── auth.py # Auth middleware (Bearer token verification)
268
+ │ ├── database.py # SQLite DB (users, usage, audit_logs, feeders)
269
+ │ └── routes/
270
+ │ ├── auth_routes.py # POST /auth/register, /auth/login
271
+ │ ├── baseline.py # GET /baseline/{system}
272
+ │ ├── optimize.py # POST /optimize
273
+ │ ├── compare.py # POST /compare
274
+ │ ├── simulate.py # POST /simulate, /simulate/toggle
275
+ │ ├── grid.py # GET /grid, POST /grid/set-out-of-service
276
+ │ ├── digital_twin.py # POST /digital-twin
277
+ │ ├── roi.py # POST /roi, GET /roi/pricing
278
+ │ ├── audit.py # GET /audit, /audit/summary
279
+ │ ├── report.py # POST /report (PDF generation)
280
+ │ ├── usage.py # GET /usage, /usage/stats
281
+ │ └── validate.py # GET /validate/{system}
282
+
283
+ ├── src/ # Core computation engine
284
+ │ ├── quantum/
285
+ │ │ ├── qaoa_reconfig.py # SA solver, QAOA solver, QUBO export
286
+ │ │ ├── hamiltonian.py # QUBO matrix construction
287
+ │ │ └── decoder.py # Decode binary strings to topologies
288
+ │ ├── ai/
289
+ │ │ ├── model.py # GraphSAGE GNN (OptiQGNN)
290
+ │ │ ├── physics_loss.py # Physics-informed + dynamic Lagrange loss
291
+ │ │ ├── train.py # Training loop with scenario generation
292
+ │ │ ├── inference.py # GNN inference on new topologies
293
+ │ │ └── dataset.py # PyG data construction
294
+ │ ├── grid/
295
+ │ │ ├── loader.py # Load IEEE test cases (33-bus, 118-bus)
296
+ │ │ ├── power_flow.py # AC power flow, topology validation
297
+ │ │ └── reconfiguration.py # Classical branch-exchange heuristic
298
+ │ ├── evaluation/
299
+ │ │ └── metrics.py # Impact, business model, Egypt scaling
300
+ │ └── hybrid/
301
+ │ └── pipeline.py # 3-stage hybrid pipeline orchestration
302
+
303
+ ├── frontend/ # React SPA
304
+ │ ├── src/
305
+ │ │ ├── App.jsx # Router + page transitions
306
+ │ │ ├── index.css # Tailwind + custom animations
307
+ │ │ ├── contexts/
308
+ │ │ │ └── AuthContext.jsx # SQLite-backed auth context
309
+ │ │ ├── services/
310
+ │ │ │ └── api.js # API client with Bearer token
311
+ │ │ ├── components/
312
+ │ │ │ ├── Navbar.jsx # Frosted glass navbar with glow effects
313
+ │ │ │ └── Footer.jsx # Animated footer
314
+ │ │ └── pages/
315
+ │ │ ├── LandingPage.jsx # Hero, features, stats, CTA
316
+ │ │ ├── DashboardPage.jsx # Optimization controls, results, charts
317
+ │ │ ├── GridViewPage.jsx # Interactive React Flow graph, out-of-service panel
318
+ │ │ ├── ROICalculatorPage.jsx # Calculate savings per feeder
319
+ │ │ ├── AuditPage.jsx # Audit log history with before/after
320
+ │ │ ├── LoginPage.jsx # Email + password sign in
321
+ │ │ ├── SignupPage.jsx # Registration form
322
+ │ │ ├── PricingPage.jsx # SaaS tier comparison
323
+ │ │ └── AboutPage.jsx # Team, methodology, tech stack
324
+ │ ├── package.json
325
+ │ ├── vite.config.js
326
+ │ └── tailwind.config.js
327
+
328
+ ├── config.py # Centralized configuration (dataclasses)
329
+ ├── requirements.txt # Python dependencies
330
+ ├── Dockerfile # Multi-stage Docker build
331
+ ├── docker-compose.yml # Docker Compose for one-command deployment
332
+ ├── .dockerignore # Docker build exclusions
333
+ ├── scripts/
334
+ │ └── benchmark.py # Full benchmark suite vs published literature
335
+ ├── models/ # Saved GNN checkpoints
336
+ ├── start.sh # Launch script (backend + ngrok)
337
+ ├── .env # Environment variables (git-ignored)
338
+ ├── .env.example # Template for environment variables
339
+ ├── optiq.db # SQLite database (auto-created)
340
+ ├── FRONTEND_SPEC.md # API contract documentation
341
+ └── REFERENCES.md # All external sources with numbered citations
342
+ ```
343
+
344
+ ---
345
+
346
+ ## Backend API Endpoints
347
+
348
+ All endpoints are prefixed with `/api`.
349
+
350
+ ### Authentication
351
+ | Method | Endpoint | Description |
352
+ |--------|----------|-------------|
353
+ | POST | `/auth/register` | Register new user (email, password, display_name) → returns token |
354
+ | POST | `/auth/login` | Login with email + password → returns token |
355
+
356
+ ### Grid & Power Flow
357
+ | Method | Endpoint | Description |
358
+ |--------|----------|-------------|
359
+ | GET | `/grid?system=case33bw` | Get grid topology (nodes + branches) for visualization |
360
+ | POST | `/grid/set-out-of-service` | Set specific lines out of service, run power flow |
361
+ | GET | `/grid/{system}/switches` | Get switch states for all lines |
362
+ | GET | `/baseline/{system}` | Run baseline AC power flow on default topology |
363
+
364
+ ### Optimization
365
+ | Method | Endpoint | Description |
366
+ |--------|----------|-------------|
367
+ | POST | `/optimize` | Run hybrid pipeline (quantum SA → GNN → AC PF) |
368
+ | POST | `/compare` | Compare Classical vs Quantum+Classical vs Full Hybrid |
369
+ | POST | `/simulate` | Run simulation with custom parameters |
370
+ | POST | `/simulate/toggle` | Toggle individual line switches |
371
+
372
+ ### Analytics & Reporting
373
+ | Method | Endpoint | Description |
374
+ |--------|----------|-------------|
375
+ | POST | `/roi` | Calculate ROI for given parameters |
376
+ | GET | `/roi/pricing` | Get SaaS pricing tiers |
377
+ | GET | `/roi/comparison` | Compare pricing models |
378
+ | GET | `/audit` | Get user's audit log history |
379
+ | GET | `/audit/summary` | Aggregated audit statistics |
380
+ | POST | `/report` | Generate downloadable PDF report |
381
+ | GET | `/report/data` | Get report data as JSON |
382
+ | GET | `/usage` | Get usage history |
383
+ | GET | `/usage/stats` | Get aggregated user stats |
384
+
385
+ ### System
386
+ | Method | Endpoint | Description |
387
+ |--------|----------|-------------|
388
+ | GET | `/health` | Health check |
389
+ | GET | `/validate/{system}` | Validate a network system |
390
+ | POST | `/digital-twin` | Run digital-twin scenario simulation |
391
+ | GET | `/digital-twin/scenarios` | Get predefined scenarios |
392
+
393
+ ---
394
+
395
+ ## Frontend Pages
396
+
397
+ | Page | Route | Description |
398
+ |------|-------|-------------|
399
+ | **Landing** | `/` | Hero section with shimmer effect, feature showcases, animated stats, CTA |
400
+ | **Login** | `/login` | Email + password sign in (SQLite-backed) |
401
+ | **Sign Up** | `/signup` | Registration with name, email, password, benefit highlights |
402
+ | **Dashboard** | `/dashboard` | System selector, optimization controls, results charts, power flow stats |
403
+ | **Grid View** | `/grid` | Interactive React Flow graph with custom BusNode components, out-of-service line panel |
404
+ | **ROI Calculator** | `/roi` | Calculate savings for given # of feeders & electricity price |
405
+ | **Audit Log** | `/audit` | Full history of optimizations with before/after loss comparison |
406
+ | **Pricing** | `/pricing` | SaaS tier comparison (Starter $199, Professional $499, Enterprise custom) |
407
+ | **About** | `/about` | Team bios, methodology explanation, technology stack cards |
408
+
409
+ ### UI Animations
410
+
411
+ All pages feature modern CSS animations defined in `index.css` and `tailwind.config.js`:
412
+
413
+ - **Page transitions:** `animate-page-in` — slide-up + fade-in on route change (keyed by pathname)
414
+ - **Staggered elements:** `stagger-1` through `stagger-5` — sequential fade-in with 100ms delays
415
+ - **Floating backgrounds:** `animate-float-slow` — decorative gradient orbs that drift vertically
416
+ - **Shimmer effect:** `animate-shimmer` — gradient sweep on hero text
417
+ - **Hover interactions:** `hover-lift` (translateY -4px) + `glow-ring` (box-shadow pulse)
418
+ - **Navbar:** `backdrop-blur-md` frosted glass with hover-glow brand icon
419
+ - **Reduced motion:** Respects `prefers-reduced-motion` media query
420
+
421
+ ---
422
+
423
+ ## Database Schema
424
+
425
+ The SQLite database (`optiq.db`) is auto-created on first run via `init_db()`.
426
+
427
+ ### `users` Table
428
+ | Column | Type | Description |
429
+ |--------|------|-------------|
430
+ | id | INTEGER PK | Auto-increment |
431
+ | firebase_uid | TEXT UNIQUE | User identifier (format: `user_<hex>`) |
432
+ | email | TEXT UNIQUE | User email |
433
+ | display_name | TEXT | Display name |
434
+ | password_hash | TEXT | SHA-256 salted password hash |
435
+ | password_salt | TEXT | Random 16-byte hex salt |
436
+ | created_at | TIMESTAMP | Registration time |
437
+ | last_login | TIMESTAMP | Last login time |
438
+ | total_optimizations | INTEGER | Cumulative optimization count |
439
+ | total_energy_saved_kwh | REAL | Cumulative energy savings |
440
+ | total_co2_saved_kg | REAL | Cumulative CO₂ savings |
441
+ | total_money_saved_usd | REAL | Cumulative cost savings |
442
+
443
+ ### `usage` Table
444
+ Tracks every optimization run: user_id, system, method, load_multiplier, baseline/optimized losses, energy/CO₂/money saved, computation time, shadow mode flag, switches changed.
445
+
446
+ ### `audit_logs` Table
447
+ Full audit trail: action, system, method, details, baseline/optimized losses, loss reduction %, annual energy/CO₂/cost savings, open lines before/after.
448
+
449
+ ### `feeders` Table
450
+ Multi-feeder management: user_id, name, system type, created_at.
451
+
452
+ ---
453
+
454
+ ## Authentication
455
+
456
+ OptiQ uses **SQLite-based authentication** (no external services required):
457
+
458
+ 1. **Registration:** `POST /api/auth/register` — hashes password with SHA-256 + random salt, creates user in `optiq.db`, returns a Bearer token.
459
+ 2. **Login:** `POST /api/auth/login` — verifies password against stored hash, returns Bearer token.
460
+ 3. **Token format:** `uid:email:displayName` — sent as `Authorization: Bearer <token>` header.
461
+ 4. **Middleware:** `api/auth.py` parses the Bearer token and injects user info into route handlers via FastAPI `Depends()`.
462
+ 5. **Frontend:** `AuthContext.jsx` manages session state via `localStorage`, syncs token with the API client.
463
+
464
+ No Firebase, no external OAuth, no third-party dependencies. The system is fully self-contained.
465
+
466
+ ---
467
+
468
+ ## Grid Visualization & Out-of-Service Lines
469
+
470
+ ### Supported Systems
471
+
472
+ | System | Buses | Lines | Topology | Layout Algorithm |
473
+ |--------|-------|-------|----------|-----------------|
474
+ | **IEEE 33-bus** | 33 | 37 (32 feeder + 5 tie) | Radial (tree) | BFS layered |
475
+ | **IEEE 118-bus** | 118 | 186 | Meshed (loops) | Kamada-Kawai |
476
+
477
+ ### Out-of-Service Lines
478
+
479
+ Users can manually set lines as out of service via the Grid View page:
480
+
481
+ - Enter line IDs in the out-of-service panel
482
+ - Click "Apply & Run Power Flow" to validate and compute results
483
+ - **Distribution networks (33-bus):** Must maintain a connected **tree** (radial) topology
484
+ - **Transmission networks (118-bus):** Only requires **connectivity** (mesh loops allowed)
485
+
486
+ The validation function `check_topology_valid()` in `power_flow.py` automatically detects the system type and enforces the appropriate constraint.
487
+
488
+ ### Visualization Features
489
+
490
+ - **Custom BusNode components** with React Flow Handle elements for proper edge connections
491
+ - **Color-coded nodes:** Slack bus (green), generator (blue), load (orange)
492
+ - **Line status indicators:** In-service (solid), out-of-service (dashed/red)
493
+ - **Interactive controls:** Pan, zoom, minimap, drag-to-rearrange
494
+
495
+ ---
496
+
497
+ ## Evaluation & Impact Metrics
498
+
499
+ ### What Gets Calculated (`src/evaluation/metrics.py`)
500
+
501
+ | Category | Metrics |
502
+ |----------|---------|
503
+ | **Power Flow** | Total losses (kW/MW), loss %, voltage profile (min/max/mean p.u.), voltage violations count, per-line loadings (%), per-line losses (kW) |
504
+ | **Optimization Impact** | Loss reduction (kW & %), annual energy saved (MWh/yr), CO₂ reduction (tonnes/yr), cost savings (USD/yr) |
505
+ | **Environmental** | Trees planted equivalent, cars removed equivalent |
506
+ | **Business Model** | SaaS revenue per feeder ($200/month), revenue-share (15%), enterprise licensing |
507
+ | **Solution Footprint** | Energy/CO₂ cost of running the optimization (150W TDP assumed) |
508
+ | **Net Benefit** | Waste eliminated minus solution overhead (typically 0.007% overhead) |
509
+ | **Dependent Variables** | ~178 physical, ~20 algorithmic, 3 external, 5 decision = 201 total |
510
+
511
+ ### Waste Elimination Framework
512
+
513
+ | Metric | Before OptiQ | After OptiQ |
514
+ |--------|-------------|-------------|
515
+ | Energy wasted as heat (per feeder/year) | 1,775,477 kWh | 1,222,458 kWh |
516
+ | **Waste eliminated** | -- | **553,020 kWh/year (31.15%)** |
517
+ | Solution computational overhead | -- | 36.5 kWh/year (0.007% of savings) |
518
+
519
+ ---
520
+
521
+ ## Egypt-Specific Scaling & Implementation
522
+
523
+ ### Scaling Parameters
524
+
525
+ | Parameter | Value | Source |
526
+ |-----------|-------|--------|
527
+ | Grid emission factor | 0.50 kg CO₂/kWh | IEA 2022 (88% natural gas) |
528
+ | Total generation | 215.8 TWh | IEA 2022 |
529
+ | T&D losses | 17 % of output | FY 2022/23 target |
530
+ | Distribution losses | 11 % of output | Estimated |
531
+ | Cairo consumption share | 27 % | Estimated |
532
+
533
+ ### Impact at Scale
534
+
535
+ | Scope | Savings | CO₂ Saved | Cost Saved |
536
+ |-------|---------|-----------|------------|
537
+ | Single feeder | 553 MWh/year | 26.3 t/year | $44K/year |
538
+ | Cairo (5,000 feeders) | 2.0 TWh/year | 1.0 Mt/year | $221M/year |
539
+ | Egypt (all feeders) | 7.4 TWh/year | 3.7 Mt/year | $592M/year |
540
+ | Global | 467 TWh/year | 222 Mt/year | -- |
541
+
542
+ ### Implementation Plan
543
+
544
+ | Phase | Timeline | Scope | Cost |
545
+ |-------|----------|-------|------|
546
+ | Phase 0 (MVP) | Done | IEEE benchmark validated | $0 |
547
+ | Phase 1 (Pilot) | 3-6 months | 5-10 feeders, NCEDC substation, shadow mode | $10-20K |
548
+ | Phase 2 (District) | 6-12 months | 100+ feeders, automated SCADA pipeline | $50-100K |
549
+ | Phase 3 (Cairo) | 1-2 years | 5,000+ feeders across NCEDC + SCEDC | $500K-1M |
550
+ | Phase 4 (National) | 2-3 years | All 9 distribution companies | $2-5M |
551
+
552
+ ### Pricing Model
553
+
554
+ | Model | Price | Value Proposition |
555
+ |-------|-------|-------------------|
556
+ | **SaaS Subscription** | $200/feeder/month | 5.4% of savings — immediate payback |
557
+ | **Revenue Share** | 15% of verified savings | ~$6,636/feeder/year, zero upfront cost |
558
+ | **Enterprise License** | $500K/year (up to 1,000 feeders) | $500/feeder/year for large utilities |
559
+
560
+ ### CO₂ Trustworthiness
561
+
562
+ Energy savings are computed from **pandapower's Newton–Raphson AC power flow** — an industry-standard, physics-validated solver derived from Kirchhoff's laws. CO₂ uses Egypt's grid factor (0.50 kg CO₂/kWh for 88% gas). Annualisation assumes constant load; real-world savings are ~60-80% of this figure due to load variation.
563
+
564
+ ---
565
+
566
+ ## Configuration
567
+
568
+ All hyperparameters are centralized in `config.py` via Python dataclasses:
569
+
570
+ | Section | Key Parameters |
571
+ |---------|---------------|
572
+ | **Grid** | `system=case33bw`, `v_min=0.95`, `v_max=1.05`, `n_tie_switches=5` |
573
+ | **Quantum** | `reps=2`, `shots=250,000`, `top_k=5`, `radiality_penalty=100`, `optimizer=COBYLA`, `maxiter=200` |
574
+ | **AI** | `hidden_dim=64`, `num_layers=3`, `dropout=0.1`, `lr=1e-3`, `epochs=200`, `n_scenarios=2000` |
575
+ | **Impact** | `emission_factor=0.475` kg CO₂/kWh, `electricity_price=$0.10/kWh`, `hours_per_year=8760` |
576
+ | **Egypt** | `emission_factor=0.50`, `total_generation=215.8 TWh`, `td_loss=17%`, `dist_loss=11%` |
577
+ | **API** | `host=0.0.0.0`, `port=8000`, `reload=True`, `cors_origins=["*"]` |
578
+
579
+ ---
580
+
581
+ ## Installation
582
+
583
+ ### Prerequisites
584
+ - Python 3.11+ (tested on 3.12)
585
+ - Node.js 18+ (for frontend build)
586
+ - pip / conda
587
+
588
+ ### Backend Setup
589
+
590
+ ```bash
591
+ # Clone the repository
592
+ git clone https://github.com/your-org/OptiQ.git
593
+ cd OptiQ
594
+
595
+ # Create virtual environment
596
+ python -m venv venv
597
+ source venv/bin/activate
598
+
599
+ # Install Python dependencies
600
+ pip install -r requirements.txt
601
+
602
+ # (Optional) Train the GNN model (~60 seconds)
603
+ python -c "
604
+ import sys; sys.path.insert(0, '.')
605
+ from src.ai.train import train
606
+ train(n_scenarios=1000, epochs=100, verbose=True)
607
+ "
608
+ ```
609
+
610
+ ### Frontend Setup
611
+
612
+ ```bash
613
+ cd frontend
614
+ npm install
615
+ npm run build # Produces frontend/dist/ served by FastAPI
616
+ cd ..
617
+ ```
618
+
619
+ ---
620
+
621
+ ## Running the Application
622
+
623
+ ### Quick Start
624
+
625
+ ```bash
626
+ # Using the start script (loads .env automatically):
627
+ ./start.sh
628
+
629
+ # Or manually:
630
+ source venv/bin/activate
631
+ python -m uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload
632
+ ```
633
+
634
+ The application is available at **http://localhost:8000**. The built React frontend is served directly from FastAPI.
635
+
636
+ ### Development (separate frontend dev server)
637
+
638
+ ```bash
639
+ # Terminal 1 — Backend
640
+ source venv/bin/activate
641
+ python -m uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload
642
+
643
+ # Terminal 2 — Frontend (with hot reload)
644
+ cd frontend
645
+ npm run dev
646
+ ```
647
+
648
+ ### Run the Benchmark
649
+
650
+ ```bash
651
+ source venv/bin/activate
652
+ python scripts/benchmark.py
653
+ ```
654
+
655
+ ---
656
+
657
+ ## Deployment with ngrok
658
+
659
+ OptiQ uses **pyngrok** (Python library) to create a public tunnel automatically on server startup — no CLI tool needed.
660
+
661
+ ### Setup
662
+
663
+ 1. Copy `.env.example` to `.env`:
664
+ ```bash
665
+ cp .env.example .env
666
+ ```
667
+
668
+ 2. Add your ngrok authtoken (get from [ngrok.com](https://ngrok.com)):
669
+ ```env
670
+ NGROK_AUTHTOKEN=your_authtoken_here
671
+ NGROK_DOMAIN=your-custom-domain.ngrok-free.app
672
+ ```
673
+
674
+ 3. Start the server — ngrok tunnel opens automatically:
675
+ ```bash
676
+ ./start.sh
677
+ ```
678
+
679
+ The console will show:
680
+ ```
681
+ ✓ ngrok tunnel open → https://your-custom-domain.ngrok-free.app
682
+ ```
683
+
684
+ If `NGROK_AUTHTOKEN` is not set, the server starts normally without a tunnel.
685
+
686
+ ### CRL Workaround
687
+
688
+ On first start, the server writes a clean ngrok v3 config with `crl_noverify: true` to work around the known CRL verification issue in ngrok v3. No manual config is needed.
689
+
690
+ ---
691
+
692
+ ## Deployment with Docker
693
+
694
+ ### Quick Start (Docker Compose)
695
+
696
+ ```bash
697
+ # Build and run
698
+ docker compose up -d
699
+
700
+ # View logs
701
+ docker compose logs -f optiq
702
+
703
+ # Stop
704
+ docker compose down
705
+ ```
706
+
707
+ The app is available at **http://localhost:8000**.
708
+
709
+ ### Build Image Only
710
+
711
+ ```bash
712
+ docker build -t optiq .
713
+ docker run -p 8000:8000 -e OPTIQ_MOCK_AUTH=true optiq
714
+ ```
715
+
716
+ ### Environment Variables via Docker
717
+
718
+ Pass any env var at runtime:
719
+
720
+ ```bash
721
+ docker run -p 8000:8000 \
722
+ -e OPTIQ_MOCK_AUTH=true \
723
+ -e NGROK_AUTHTOKEN=your_token \
724
+ -e NGROK_DOMAIN=your-domain.ngrok-free.app \
725
+ -v optiq-data:/app/data \
726
+ optiq
727
+ ```
728
+
729
+ ### Docker Architecture
730
+
731
+ The image uses a **multi-stage build**:
732
+ 1. **Stage 1 (Node 20):** Builds the React frontend → `frontend/dist/`
733
+ 2. **Stage 2 (Python 3.12-slim):** Installs Python dependencies + copies source + built frontend
734
+
735
+ The `docker-compose.yml` persists the SQLite database and GNN models via named volumes.
736
+
737
+ ---
738
+
739
+ ## Environment Variables
740
+
741
+ Create a `.env` file (or copy from `.env.example`):
742
+
743
+ | Variable | Default | Description |
744
+ |----------|---------|-------------|
745
+ | `NGROK_AUTHTOKEN` | _(empty)_ | ngrok authentication token (optional) |
746
+ | `NGROK_DOMAIN` | _(empty)_ | Custom ngrok domain (optional) |
747
+ | `PORT` | `8000` | Server port |
748
+ | `OPTIQ_MOCK_AUTH` | `true` | `true` = accept any Bearer token; `false` = verify against SQLite |
749
+
750
+ ---
751
+
752
+ ## Tech Stack
753
+
754
+ ### Backend
755
+ | Technology | Version | Purpose |
756
+ |-----------|---------|---------|
757
+ | **Python** | 3.12 | Runtime |
758
+ | **FastAPI** | 0.128+ | REST API framework |
759
+ | **uvicorn** | 0.40+ | ASGI server |
760
+ | **pandapower** | 3.4+ | AC power flow (Newton–Raphson), IEEE test cases |
761
+ | **Qiskit** | 2.3+ | Quantum computing (QAOA circuits, QUBO) |
762
+ | **PyTorch** | 2.9+ | GNN training & inference |
763
+ | **PyTorch Geometric** | 2.7+ | Graph neural network layers (SAGEConv) |
764
+ | **NetworkX** | 3.4+ | Graph algorithms (topology validation, layouts) |
765
+ | **SQLite** | built-in | User database, usage tracking, audit logs |
766
+ | **pyngrok** | 7.0+ | ngrok tunnel from Python (public URL) |
767
+ | **python-dotenv** | 1.0+ | Load .env environment variables |
768
+
769
+ ### Frontend
770
+ | Technology | Version | Purpose |
771
+ |-----------|---------|---------|
772
+ | **React** | 18.3 | UI library |
773
+ | **Vite** | 5.4 | Build tool & dev server |
774
+ | **Tailwind CSS** | 3.4 | Utility-first CSS framework |
775
+ | **React Flow** | 11.11 | Interactive graph visualization |
776
+ | **Recharts** | 2.13 | Charts & data visualization |
777
+ | **Lucide React** | 0.460 | Icon library |
778
+ | **React Router** | 6.28 | Client-side routing |
779
+
780
+ ---
781
+
782
+ ## References
783
+
784
+ 1. Baran & Wu, "Network reconfiguration in distribution systems for loss reduction and load balancing," IEEE Trans. Power Delivery, 1989.
785
+ 2. Civanlar et al., "Distribution feeder reconfiguration for loss reduction," IEEE Trans. Power Delivery, 1988.
786
+ 3. Goswami & Basu, "A new algorithm for the reconfiguration of distribution feeders for loss minimization," IEEE Trans. Power Delivery, 1992.
787
+ 4. Jabr et al., "Minimum Loss Network Reconfiguration Using Mixed-Integer Convex Programming," IEEE Trans. Power Systems, 2012.
788
+ 5. Sulaima et al., "A DNR for loss minimization by using improved PSO," IJICIC, 2014.
789
+ 6. Pereira et al., "Branch Exchange + Clustering," Applied Sciences, 2023.
790
+ 7. Various authors — GA, SA, and other metaheuristics for IEEE 33-bus reconfiguration.
791
+ 8. Qiskit SDK 2.x — Migration from 1.x to 2.x (arXiv:2512.08245).
792
+ 9. Egyptian Electricity Holding Company (EEHC) annual reports.
793
+ 10. Hamilton et al., "Inductive Representation Learning on Large Graphs," NeurIPS 2017 (GraphSAGE).
794
+ 11. Thurner et al., "pandapower — An Open-Source Python Tool for Convenient Modeling, Analysis, and Optimization of Electric Power Systems," IEEE Trans. Power Systems, 2018.
795
+ 12. IEA Egypt Energy Data, Country profile 2022.
796
+ 13. DeepOPF-NGT — Physics-informed neural network with dynamic Lagrange multipliers.
797
+
798
+ All bracketed numbers (e.g. [1], [12]) refer to the [References](#full-references) section below for full citations.
799
+
800
+ ---
801
+
802
+ ## Full References
803
+
804
+ All externally-sourced numbers in this project are listed below with their original source.
805
+
806
+ ### IEEE 33-Bus Test System
807
+
808
+ - **[1]** M. E. Baran and F. F. Wu, "Network reconfiguration in distribution systems for loss reduction and load balancing," *IEEE Trans. Power Delivery*, vol. 4, no. 2, pp. 1401-1407, Apr. 1989. — Source of the IEEE 33-bus benchmark. Base case losses: 202.67 kW. Optimal reconfiguration: 139.55 kW (31.15% reduction). Open switches: 7, 9, 14, 32, 37 (1-indexed).
809
+ - **[2]** S. Civanlar et al., "Distribution feeder reconfiguration for loss reduction," *IEEE Trans. Power Delivery*, 1988. — Load-transfer heuristic. ~146 kW on 33-bus.
810
+ - **[3]** S. K. Goswami and S. K. Basu, "A new algorithm for the reconfiguration of distribution feeders for loss minimization," *IEEE Trans. Power Delivery*, 1992. — ~139.55 kW on 33-bus.
811
+ - **[4]** R. S. Jabr et al., "Minimum loss network reconfiguration using mixed-integer convex programming," *IEEE Trans. Power Systems*, 2012. — MILP exact: 139.55 kW.
812
+ - **[5]** M. F. Sulaima et al., "A DNR by Using Rank Evolutionary PSO for Power Loss Minimization," *ISMS*, 2014. — PSO: 146.1 kW (local optimum).
813
+ - **[6]** E. C. Pereira et al., "Distribution Network Reconfiguration Using Iterative Branch Exchange and Clustering Technique," *Energies*, 2023. — 139.55 kW. Applied to 81 real feeders at CEMIG-D (Brazil).
814
+ - **[7]** F. Bohigas-Daranas et al., "Open-source implementation of distribution network reconfiguration methods," *arXiv:2511.22957*, 2025. — Compares 7 methods, confirms 139.55 kW optimal.
815
+ - **[8]** S. H. Dolatabadi et al., "An Enhanced IEEE 33 Bus Benchmark Test System," *IEEE Trans. Power Systems*, 2021. — Enhanced 33-bus with DG, total load 3.715 MW.
816
+
817
+ ### Distribution Loss Reduction: Industry Practice
818
+
819
+ - **[9]** "Power Distribution Network Reconfiguration Techniques: A Thorough Review," *Sustainability*, 2024. — Survey of 200+ articles. Manual: 5-10%. Automated: 25-34%.
820
+ - **[10]** Bohigas-Daranas et al., 2025 (same as [7]). Confirms 25-34% on real networks.
821
+ - **[11]** "Operational Cost Minimization of Electrical Distribution Network during Switching for Sustainable Operation," *Sustainability*, 2022. — MISOCP on real 71-bus Malaysian network: 25.5%.
822
+
823
+ ### Egypt Energy Data
824
+
825
+ - **[12]** IEA, "Egypt — Countries & Regions," 2022. — Total generation: 215.8 TWh. Natural gas: 81%.
826
+ - **[13]** "Egypt plans to reduce electricity network loss to 16.83% in FY23/24," *Egypt Today*, 2023. — T&D losses: 22.19% (FY 2021/22), target 16.83%.
827
+ - **[14]** CEIC, "Egypt: Electric Power T&D Losses: % of Output." — Historical losses: 11.15% (2014), 22.16% (1985).
828
+ - **[15]** EEHC, "Geographical distribution of electricity distribution companies." — 9 regional distribution companies.
829
+ - **[16]** Iskraemeco, "Improving energy efficiency — NCEDC." — 500,000 smart meters, AMI, SCADA.
830
+ - **[17]** PRIME Alliance, "PRIME 1.4 Roll-out of 63,000 Smart Meters in Egypt," 2022. — 300,000 more planned.
831
+
832
+ ### Global Data & Emission Factors
833
+
834
+ - **[18]** IEA, "Electricity 2025 — Supply." — Global demand grew 4.3% in 2024.
835
+ - **[19]** World Bank, "Electric power T&D losses (% of output)." — Global: 7-10%.
836
+ - **[20]** IEA, "Emission Factors." — Global average: 0.475 kg CO₂/kWh.
837
+ - **[21]** Egypt grid emission factor: ~0.50 kg CO₂/kWh (derived from 88% gas).
838
+ - **[22]** Strategic Market Research, "ADMS Market, 2024-2030." — $3.8B (2024), projected $10.5B by 2030.
839
+ - **[23]** Intent Market Research, "ADMS Market, 2024-2030." — Cloud-based ADMS fastest-growing.
840
+ - **[24]** U.S. EPA, "Greenhouse Gas Equivalencies Calculator." — 21 kg CO₂/tree/year, 4.6 t CO₂/car/year.
841
+
842
+ ### Power System Simulation
843
+
844
+ - **[25]** L. Thurner et al., "pandapower — An Open-Source Python Tool for Power Systems," *IEEE Trans. Power Systems*, 2018. — Newton-Raphson AC power flow solver.
845
+ - **[26]** MATPOWER, "case33bw — Baran & Wu 33-bus system." — 33 buses, 37 lines, 12.66 kV, 3.715 MW.
846
+
847
+ ---
848
+
849
+ ## API Contract (Frontend Specification)
850
+
851
+ > Detailed request/response examples for frontend integration.
852
+
853
+ ### Baseline Endpoint
854
+
855
+ ```
856
+ GET /api/baseline/{system} (system = "case33bw" | "case118")
857
+ ```
858
+
859
+ **Response** (key fields):
860
+ ```json
861
+ {
862
+ "system": "case33bw",
863
+ "network": { "n_buses": 33, "n_lines": 37, "n_tie_lines": 5, "total_load_mw": 3.715 },
864
+ "power_flow": {
865
+ "converged": true, "total_loss_kw": 202.68, "loss_pct": 5.17,
866
+ "min_voltage_pu": 0.9131, "voltage_violations": 21,
867
+ "bus_voltages": [1.0, 0.997, "..."],
868
+ "line_loadings_pct": [47.2, "..."],
869
+ "line_losses_kw": [12.5, "..."]
870
+ },
871
+ "buses": [{ "index": 0, "vn_kv": 12.66, "load_mw": 0.0, "is_slack": true }, "..."],
872
+ "lines": [{ "index": 0, "from_bus": 0, "to_bus": 1, "in_service": true, "is_tie": false }, "..."]
873
+ }
874
+ ```
875
+
876
+ ### Optimize Endpoint
877
+
878
+ ```
879
+ POST /api/optimize
880
+ Body: { "system": "case33bw", "method": "hybrid", "quantum_iters": 300 }
881
+ ```
882
+
883
+ **Response** includes `baseline`, `optimized` (with `open_lines`), `impact` (loss reduction, CO₂, cost), `candidates`, and `timings`.
884
+
885
+ ### Compare Endpoint
886
+
887
+ ```
888
+ POST /api/compare
889
+ Body: { "system": "case33bw", "methods": ["classical", "quantum", "hybrid"] }
890
+ ```
891
+
892
+ **Response** includes per-method `optimized`, `impact`, and `time_sec`.
893
+
894
+ ### Grid Endpoints
895
+
896
+ ```
897
+ GET /api/grid?system=case33bw → nodes + branches for React Flow
898
+ POST /api/grid/set-out-of-service → set lines OOS, run power flow
899
+ GET /api/grid/{system}/switches → switch states for all lines
900
+ ```
901
+
902
+ ### Additional Endpoints
903
+
904
+ | Method | Endpoint | Purpose |
905
+ |--------|----------|---------|
906
+ | POST | `/api/simulate` | Custom switch configuration |
907
+ | POST | `/api/simulate/toggle` | Toggle single switch |
908
+ | POST | `/api/digital-twin` | Scenario simulation |
909
+ | POST | `/api/roi` | ROI calculation |
910
+ | POST | `/api/report` | Generate HTML report |
911
+ | GET | `/api/audit` | Audit log history |
912
+ | GET | `/api/usage` | Usage statistics |
913
+
914
+ ---
915
+
916
+ <p align="center">
917
+ Built with ⚡ by the OptiQ Team
918
+ </p>
requirements.txt ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OptiQ — Hybrid Quantum-AI-Classical Grid Optimization
2
+ # Tested on Python 3.11 + conda (projects env)
3
+
4
+ # Power system simulation
5
+ pandapower>=3.4.0
6
+ numba>=0.63.0
7
+
8
+ # Quantum optimization (Qiskit 2.x ecosystem)
9
+ qiskit>=2.3.0
10
+ qiskit-optimization>=0.7.0
11
+
12
+ # AI / GNN (PyTorch Geometric)
13
+ # PyTorch 2.9+cu128 installed via conda separately
14
+ torch-geometric>=2.7.0
15
+
16
+ # API
17
+ fastapi>=0.128.0
18
+ uvicorn[standard]>=0.40.0
19
+ python-multipart>=0.0.20
20
+ python-dotenv>=1.0.0
21
+
22
+ # Visualization & data
23
+ plotly>=6.5.0
24
+ numpy>=2.3.0
25
+ pandas>=2.3.0
26
+ scipy>=1.16.0
27
+ networkx>=3.4.0