Power System Simulation Using Python: A Step-by-Step Guide

Step-by-step guide to simulating power systems using Python, PyPSA, and Pandapower libraries.

The ability to simulate and analyze power systems is critical in modern electrical engineering. From grid expansion planning to load flow and fault analysis, simulation allows engineers to optimize design, ensure stability, and prepare for contingencies. Traditionally, such simulations were done using proprietary software like ETAP, PSS®E, and DIgSILENT PowerFactory. However, the rise of Python in scientific computing has opened the doors to powerful, open-source tools for power system analysis.

This guide provides a step-by-step walk-through on modeling, simulating, and analyzing power systems using Python—with a focus on technical accuracy, extensibility, and practical applications.

1. Overview of Power System Simulation

Why Simulate Power Systems?

Power systems are dynamic and complex. Simulation helps in:

  • Understanding the steady-state behavior (load flow)

  • Analyzing faults and contingency scenarios

  • Performing stability studies

  • Evaluating economic dispatch and optimal power flow

  • Planning grid expansion and renewable integration

Python-based tools offer the ability to customize simulations, automate workflows, and integrate with machine learning pipelines.

2. Mathematical Foundation: Power Flow Equations

Power flow (load flow) analysis solves for voltage magnitude and angle at each bus, given power injections and line parameters. The non-linear power flow equations are:

Pi=Vij=1nVj(Gijcosθij+Bijsinθij)P_i = V_i \sum_{j=1}^{n} V_j (G_{ij} \cos \theta_{ij} + B_{ij} \sin \theta_{ij}) Qi=Vij=1nVj(GijsinθijBijcosθij)Q_i = V_i \sum_{j=1}^{n} V_j (G_{ij} \sin \theta_{ij} - B_{ij} \cos \theta_{ij})

Where:

  • Pi,QiP_i, Q_i: real and reactive power injections at bus i

  • Vi,θiV_i, \theta_i: voltage magnitude and angle at bus i

  • Gij,BijG_{ij}, B_{ij}: real and imaginary parts of the admittance matrix YbusY_{bus}

Numerical methods like Newton-Raphson and Gauss-Seidel are used to solve these equations.

3. Python Libraries for Power System Simulation

Library Purpose
NumPy Efficient array/matrix operations
SciPy Non-linear solvers and sparse matrix support
Matplotlib / Plotly Visualizations
Pandas Tabular data management
PyPSA Open-source library for power flow, OPF, and planning
Pandapower For grid modeling with switchgear and fault analysis
NetworkX For custom graph-based power networks

In this guide, we’ll use PyPSA for steady-state power flow and OPF simulations.

4. Modeling a Power System in PyPSA

Step 1: Install Required Libraries

pip install pypsa numpy pandas matplotlib

Step 2: Create a Network

import pypsa

net = pypsa.Network()
net.set_snapshots(range(1))  # single time snapshot

Step 3: Add Buses

net.add("Bus", "Bus 1", v_nom=110)
net.add("Bus", "Bus 2", v_nom=110)
net.add("Bus", "Bus 3", v_nom=110)

Step 4: Add Transmission Lines

Transmission lines are added with series impedance R+jXR + jX, and shunt susceptance BB.

net.add("Line", "1-2", bus0="Bus 1", bus1="Bus 2", r=0.01, x=0.1, b=0.001, s_nom=100)
net.add("Line", "2-3", bus0="Bus 2", bus1="Bus 3", r=0.01, x=0.1, b=0.001, s_nom=100)

Step 5: Add Generators

net.add("Generator", "Gen 1", bus="Bus 1", p_set=80, control="PQ", marginal_cost=20)

Step 6: Add Loads

net.add("Load", "Load 3", bus="Bus 3", p_set=60, q_set=25)

5. Running a Load Flow Simulation

PyPSA uses linear (DC) or non-linear (AC) power flow solvers. Here’s how to run an AC power flow:

net.pf()  # AC power flow using Newton-Raphson

After running the power flow, we can inspect bus voltages, line loading, and power flows.

print(net.buses_t.v_mag_pu)
print(net.lines_t.p0)  # Real power flow at sending end

6. Example: Voltage and Power Flow Visualization

import matplotlib.pyplot as plt

voltages = net.buses_t.v_mag_pu.iloc[0]
voltages.plot(kind='bar', title='Bus Voltage Magnitudes (p.u.)', color='skyblue')
plt.ylabel("Voltage (p.u.)")
plt.grid(True)
plt.show()

Similarly, line flows can be plotted to understand loading conditions.

7. Time-Series Load Flow (e.g., Solar Profile)

You can simulate 24-hour variation in load and generation:

import numpy as np
import pandas as pd

snapshots = pd.date_range("2025-01-01", periods=24, freq="H")
net.set_snapshots(snapshots)

# Solar generation profile (sinusoidal)
gen_profile = 50 + 30*np.maximum(0, np.sin(np.linspace(0, 2*np.pi, 24)))

# Load profile (static for now)
load_profile = [60]*24

net.generators_t.p_set["Gen 1"] = gen_profile
net.loads_t.p_set["Load 3"] = load_profile

net.pf()  # Solve for all time steps

You can now analyze how grid voltages or flows change over the day.

8. Optimal Power Flow (OPF)

PyPSA can solve DC OPF problems using linear programming to minimize generation cost while satisfying load and line constraints.

net.generators.loc["Gen 1", "marginal_cost"] = 30
net.generators.loc["Gen 1", "p_nom"] = 100
net.loads.loc["Load 3", "p_set"] = 60

net.lopf()
print(net.objective)  # Total cost

To make it more interesting, add another generator:

net.add("Generator", "Gen 2", bus="Bus 2", p_nom=100, marginal_cost=10)
net.lopf()

PyPSA will now dispatch the cheaper generator (Gen 2) more.

9. Exporting Simulation Data

net.buses_t.v_mag_pu.to_csv("bus_voltages.csv")
net.lines_t.p0.to_csv("line_flows.csv")

This is helpful for generating reports or integrating with dashboards.

10. Advanced Simulation Ideas

  • Fault Analysis: Use pandapower for short-circuit calculations using IEC 60909 standard.

  • Contingency Simulation: Remove a line and check how system behaves.

  • Grid Expansion Planning: Add candidate lines and use lopf with cost constraints.

  • Renewable Energy Modeling: Load time-series solar/wind profiles from CSV.

FAQs

Q1: How scalable is PyPSA for large networks?

PyPSA supports sparse matrix solvers and can simulate national-scale networks with thousands of buses efficiently. It has been used in modeling European transmission networks.

Q2: How does PyPSA compare to commercial tools like PSS®E?

While PSS®E supports advanced dynamic and protection simulations, PyPSA excels at planning, OPF, and flexibility. It also allows full transparency and integration with other Python tools (e.g., ML, databases).

Q3: Can I simulate battery storage or EV charging?

Yes. PyPSA supports storage units with constraints like state-of-charge, efficiency, and charging/discharging limits.

net.add("StorageUnit", "Battery 1", bus="Bus 2", p_nom=20, max_hours=2, efficiency_store=0.9)

Q4: Is Python fast enough for real-time control?

For offline simulation, Python is excellent. For real-time control, use Python for prototyping and convert performance-critical parts to C/C++ or use JIT compilers like Numba.

Q5: Where can I find standard test systems?

IEEE 9, 14, 30-bus systems are available in open repositories and can be modeled in PyPSA or Pandapower.

Conclusion

Python, with its mature ecosystem and open-source libraries like PyPSA and Pandapower, offers a powerful alternative for power system simulation. It enables deep customization, integration with modern technologies (like machine learning), and supports academic and industrial use cases.

Whether you're a student, researcher, or power systems engineer, Python can empower your workflow with flexible, reproducible, and scalable simulations.

Prasun Barua is an Engineer (Electrical & Electronic) and Member of the European Energy Centre (EEC). His first published book Green Planet is all about green technologies and science. His other …

Post a Comment

© Prasun Barua . All rights reserved. Developed by Jago Desain