Written and maintained by CASRAI Editorial Board
Published
On this page
PyPSA (Python for Power System Analysis) is an open-source software toolbox designed for simulating and optimizing modern electrical power systems and sector-coupled energy networks across multi-period investment and operational dispatch horizons. Built in Python and licensed under the permissive MIT License, PyPSA combines component-based network topology modeling with linearized DC optimal power flow, non-linear AC power flow, and multi-carrier sector coupling spanning electricity, district heating, synthetic gas, and hydrogen infrastructure.
Definition and scope of PyPSA
PyPSA was created to address the structural modeling challenges introduced by variable renewable energy sources, distributed generation, and cross-sector decarbonization. Traditional power system simulation packages were historically engineered around centralized, synchronous fossil-fuel and nuclear generation plants, emphasizing steady-state AC load flow calculations or proprietary mixed-integer unit commitment. As power grids transition toward high shares of inverter-based resources (such as wind turbines and solar photovoltaics) and flexible demand (such as heat pumps and battery energy storage systems), researchers and system planners require analytical tools that can simultaneously evaluate operational power flow physics and long-term capital capacity expansion across multi-regional geographic territories.
Developed primarily by research teams led by Tom Brown and contributors across Europe, PyPSA is distributed under the open-source MIT License (having transitioned from GPLv3 with version 0.18.0) with documentation licensed under Creative Commons Attribution 4.0 International (CC-BY-4.0). Academic institutions exploring open-source software licensing in university technology transfer frequently cite PyPSA as an exemplary model of public-good research software that accelerates reproducible computational science. Its landmark software architecture was peer-reviewed and published in the Journal of Open Source Software (JOSS) and the Journal of Open Research Software by Brown, Hörsch, and Schlachtberger in 2018.
The scope of PyPSA spans three interconnected analytical domains:
- Static Power Flow (PF): Calculating steady-state voltages, angles, active power, and reactive power across alternating current (AC) and direct current (DC) transmission and distribution circuits using non-linear Newton-Raphson techniques or linear DC approximations.
- Linear Optimal Power Flow (LOPF): Optimizing the economic dispatch of dispatchable generators, curtailment of renewable generation, storage charge-discharge cycles, and transmission line flows over sequential hourly or sub-hourly time snapshots.
- Capacity Expansion Planning: Co-optimizing capital investment expenditures (CAPEX) for new generation, storage, and transmission assets alongside operational expenditures (OPEX) over multi-period or multi-year investment horizons subject to technical, operational, and carbon emissions constraints.
How PyPSA works: Component architecture and mathematical formulation
At the center of any PyPSA model is the container class pypsa.Network. PyPSA structures power networks as directed multigraphs whose physical assets and operational constraints are represented as standardized tables stored as pandas.DataFrame objects. This design leverages Python’s scientific computing stack, enabling direct vectorization, fast indexing, and seamless integration with numerical data analysis libraries.
Core network components
PyPSA abstracts physical energy systems into fundamental constituent elements categorized into nodes, branches, and single-bus injection assets:
- Buses (
network.buses): The fundamental nodes of the network. Every generator, load, branch, and storage element must connect to at least one bus. Buses enforce energy conservation (Kirchhoff’s Current Law) and track nodal marginal prices, voltage magnitudes, and voltage phase angles. In multi-energy models, buses carry specific carrier labels such as AC, DC, heat, hydrogen, or natural gas. - Lines (
network.lines): Passive AC transmission lines connecting two electrical buses (bus0andbus1). Lines are parameterized by series resistance r, series reactance x, shunt susceptance b, and nominal thermal capacity rating s_nom. - Transformers (
network.transformers): AC transformers connecting buses of differing nominal voltages, incorporating turns ratios, phase shifts, and impedance parameters. - Links (
network.links): Versatile, controllable branch components that connect two or more buses (bus0,bus1, and optional tertiary ports such asbus2). Unlike passive lines, links permit directed energy conversion with defined efficiencies (η). Links model high-voltage direct current (HVDC) transmission lines, electrolyzers converting power to hydrogen, gas turbines converting methane to electricity, and heat pumps transferring heat. - Generators (
network.generators): Energy injection units attached to a single bus. Generators represent dispatchable power plants with marginal costs and ramp limits, or variable renewable resources whose hourly availability is bounded by weather-driven time-series capacity factors (p_max_pu). - Loads (
network.loads): Power sinks attached to a single bus that withdraw energy according to predetermined chronological demand profiles or price-elastic curves. - Storage Units and Stores (
network.storage_units,network.stores): PyPSA distinguishes between two storage paradigms. Storage Units model integrated storage facilities (such as pumped hydro or battery systems) where power and energy capacities are linked through maximum hours of storage. Stores model generic pure energy reservoirs (such as hydrogen salt caverns or thermal hot water tanks) that hold energy volume, while separate Links govern charge and discharge rates.
Mathematical formulation: DC power flow and optimal dispatch
For computationally intensive optimization studies spanning thousands of network buses and 8,760 hourly time steps per year, full AC non-linear power flow formulations are non-convex and computationally prohibitive for global optimization. PyPSA therefore employs the linearized DC power flow approximation for network transmission constraints.
In the DC approximation, reactive power flows and voltage magnitude variations are neglected, line resistances are assumed to be negligible compared to reactances (r ≪ x), and voltage angle differences across branches are assumed to be small (sin(θ0 − θ1) ≈ θ0 − θ1). The active power flow Pℓ across line ℓ connecting bus i and bus j with series reactance xℓ is expressed linearly as:
Pℓ = (θi − θj) / xℓ
PyPSA supports both the angle formulation (where bus phase angles θ are explicit decision variables) and the cycle formulation. In the cycle formulation, Kirchhoff’s Voltage Law (KVL) is enforced across independent cycles of the network graph (∮ xℓ Pℓ dℓ = 0), reducing the number of variables and accelerating solver convergence on sparse transmission topologies.
In a Linear Optimal Power Flow (LOPF) problem with capacity expansion, the objective function minimizes total annualized system costs across all operational snapshots t ∈ T and candidate assets n ∈ N:
Minimize: ∑n cn × Gn + ∑t ∑n wt × on × gn,t
Where cn represents annualized capital cost (CAPEX), Gn is the optimized capacity of asset n, wt is the snapshot duration weighting, on is marginal operational cost (OPEX), and gn,t is power dispatch at time t. The optimization satisfies operational constraints including:
- Nodal power balance (Kirchhoff’s Current Law) at every bus i and snapshot t: ∑ gi,t − ∑ di,t + ∑ Pin,t − ∑ Pout,t = 0
- Generation dispatch limits: 0 ≤ gn,t ≤ Gn × p_max_pun,t
- Branch thermal capacity limits: −Sℓ ≤ Pℓ,t ≤ Sℓ
- Storage state-of-charge conservation: Et = Et−1 × (1 − ηloss) + ηin Pcharge,t − (1 / ηout) Pdischarge,t
- System-wide cumulative CO2 emission ceilings: ∑t ∑n en × gn,t ≤ CapCO2
The Linopy optimization backend
Historically, PyPSA used the open-source Pyomo optimization framework to construct algebraic modeling equations. While Pyomo provided extensive modeling flexibility, converting millions of time-series constraints into algebraic expressions incurred substantial Python interpreter overhead and memory bottlenecks during model generation. To overcome this limitation, PyPSA transitioned to Linopy, an open-source optimization library designed specifically for linear, integer, and quadratic programming with N-dimensional labeled arrays based on xarray and pandas.
Linopy builds mathematical constraint matrices directly in vectorized C and NumPy memory space, reducing memory footprints by up to 70% and accelerating model generation by over an order of magnitude compared to traditional scalar-based algebraic modeling frameworks. Linopy directly exports problem formulations to leading open-source solvers (such as HiGHS and Cbc) and commercial solvers (such as Gurobi, Mosek, and CPLEX).
Sector coupling and multi-carrier infrastructure modeling
One of PyPSA’s most distinctive capabilities is its native representation of multi-carrier sector coupling. Decarbonizing the energy system requires electrifying heating, transport, and industrial processes while integrating energy carriers that can provide long-duration seasonal storage.
In PyPSA, sector coupling is modeled using multi-port Link components that bridge distinct energy carriers. For instance, an industrial electrolyzer is represented as a Link with bus0 connected to an electricity bus and bus1 connected to a hydrogen bus, parameterized with a conversion efficiency of 70% (η = 0.70). A combined-heat-and-power (CHP) plant or fuel cell can be modeled using a tertiary port (bus2), defining simultaneous electrical and thermal energy production efficiencies.
PyPSA powers prominent continental-scale research projects including:
- PyPSA-Eur: An open-source model dataset of the European power and energy system covering 33 ENTSO-E member countries, built from open transmission grid maps, Eurostat energy balances, and weather reanalysis datasets.
- PyPSA-Earth: An open global energy system model designed to provide data-sparse developing countries with open-access energy planning infrastructure.
- Atlite: An open-source Python companion library that converts historical ERA5 atmospheric reanalysis and SARAH satellite radiation data into renewable capacity factor time series (p_max_pu) for wind and solar assets mapped to PyPSA bus coordinates.
Comparative analysis: PyPSA vs. other energy modeling toolboxes
Researchers, energy laboratories, and system planners choose between several open-source energy modeling packages depending on their specific technical focus, grid level, and physical modeling fidelity. The table below illustrates the primary architectural distinctions between PyPSA, pandapower, Calliope, and OSeMOSYS.
| Feature and Dimension | PyPSA | pandapower | Calliope | OSeMOSYS |
|---|---|---|---|---|
| Core Modeling Purpose | Multi-period capacity expansion and transmission dispatch | Electrical grid operational analysis and distribution planning | Multi-vector energy system design and capacity expansion | Long-term regional energy policy and macro capacity pathways |
| Grid Power Flow Physics | Linearized DC power flow (reactances and angles); AC Newton-Raphson | Full non-linear AC Newton-Raphson and unbalanced 3-phase flow | Transport model (pipe/wire capacity limits without impedances) | Transport commodity balance (no transmission line impedances) |
| Sector Coupling Scope | Native multi-port Links (electricity, heat, gas, hydrogen) | Limited (primarily electrical transmission and distribution) | Extensive modular multi-carrier conversion nodes | Comprehensive macro-level multi-fuel energy balances |
| Temporal Horizon | Chronological multi-period (hourly 8,760 hours or multi-year) | Snapshot operational analysis (with optional time loops) | Chronological multi-period (flexible temporal clustering) | Multi-year planning with representative seasonal timeslices |
| Optimization Engine | Linopy (vectorized xarray) and Pyomo | SciPy numerical root-finding and custom algorithms | Pyomo optimization framework | GNU MathProg, PuLP, and Pyomo |
| Primary Solvers | HiGHS, Gurobi, Cbc, GLPK, CPLEX | SciPy, Newton-Raphson, Optigraph | Gurobi, HiGHS, Cbc, GLPK | GLPK, CBC, CPLEX, Gurobi |
| Software License | MIT License | BSD-3-Clause | Apache-2.0 | Apache-2.0 |
As summarized above, PyPSA is specifically optimized for scenarios where transmission line reactances and power flow bottlenecks directly influence long-term investment decisions. When researchers require detailed distribution grid voltage stability, transformer tap-changer modeling, or short-circuit analysis, pandapower is the appropriate tool. Conversely, when broad technological trade-offs across municipal or regional multi-energy vectors take priority without requiring electrical network physics, Calliope or OSeMOSYS provide flexible frameworks.
For cross-platform tool evaluation, the data table below compares these and additional frameworks across their formal release timelines, license governance, and optimization architectures.
Practical applications in research facilities and laboratory operations
Modern scientific laboratories, university campuses, and supercomputing research centers are increasingly evaluating microgrid design, local clean power generation, and resilience against grid outages. PyPSA plays a valuable operational role in research facility management and energy laboratory experiments.
Campus microgrid sizing and battery optimization
Major research institutions operating particle accelerators, cleanrooms, and high-performance computing (HPC) clusters face volatile peak electricity tariffs and stringent reliability requirements. Facility engineers use PyPSA to formulate campus microgrid models that evaluate:
- Battery Energy Storage System (BESS) Sizing: Optimizing megawatt (MW) power inverter capacity and megawatt-hour (MWh) storage volume to perform peak-shaving during high-demand experimental runs.
- Solar PV and Combined Cooling/Heating Integration: Coupling onsite rooftop solar generation with campus central chiller and boiler plants using multi-port Links to simulate thermal storage and absorption chillers.
- Building-to-Grid Dynamic Interaction: Pairing PyPSA dispatch schedules with whole-building thermodynamic simulations generated by EnergyPlus building energy simulation and OpenStudio energy modeling platform workflows to minimize campus operational greenhouse gas emissions.
Laboratory testbench and hardware-in-the-loop validation
In power systems and renewable energy research laboratories, experimental benches validate physical inverter controls, synchrophasor measurements (PMUs), and protective relaying. PyPSA serves as the macro-system simulation layer in these environments. Researchers generate optimal 24-hour transmission dispatch profiles in PyPSA, which are subsequently fed into real-time digital simulators (RTDS) or physical laboratory microgrids to test hardware-in-the-loop (HIL) responses under simulated renewable curtailment or transmission line tripping events.
Step-by-step implementation and worked code example
To demonstrate PyPSA’s programmatic interface and Linopy optimization workflow, the following worked example initializes a 3-bus network consisting of an electrical load center, a remote wind resource, a natural gas peaker plant, and a battery storage unit. The script formulates and solves a 3-period Linear Optimal Power Flow problem with capacity expansion using the open-source HiGHS solver.
import pypsa
import pandas as pd
# 1. Initialize empty Network container
network = pypsa.Network()
# 2. Define chronological simulation snapshots
snapshots = pd.date_range("2026-01-01 00:00", periods=3, freq="h")
network.set_snapshots(snapshots)
# 3. Add electrical buses
network.add("Bus", "Bus 1 - Urban Hub", v_nom=220)
network.add("Bus", "Bus 2 - Wind Farm", v_nom=220)
network.add("Bus", "Bus 3 - Storage and Gas", v_nom=220)
# 4. Add transmission lines with electrical reactance
network.add("Line", "Line 1-2", bus0="Bus 1 - Urban Hub", bus1="Bus 2 - Wind Farm", x=0.10, s_nom=100)
network.add("Line", "Line 2-3", bus0="Bus 2 - Wind Farm", bus1="Bus 3 - Storage and Gas", x=0.15, s_nom=100)
network.add("Line", "Line 3-1", bus0="Bus 3 - Storage and Gas", bus1="Bus 1 - Urban Hub", x=0.12, s_nom=100)
# 5. Add electrical load at Urban Hub
network.add("Load", "Urban Demand", bus="Bus 1 - Urban Hub", p_set=[120.0, 160.0, 140.0])
# 6. Add variable wind generation with capacity factor profile
network.add(
"Generator", "Offshore Wind",
bus="Bus 2 - Wind Farm",
p_nom_extendable=True, # Optimize capital capacity expansion
capital_cost=1200.0, # Annualized CAPEX in $/MW
marginal_cost=2.0, # Operational OPEX in $/MWh
p_max_pu=[0.90, 0.40, 0.70] # Hourly normalized availability
)
# 7. Add natural gas generator for peaking support
network.add(
"Generator", "Gas Peaker",
bus="Bus 3 - Storage and Gas",
p_nom=150.0,
p_nom_extendable=False,
marginal_cost=65.0 # Fuel OPEX in $/MWh
)
# 8. Add battery storage unit
network.add(
"StorageUnit", "Grid Battery",
bus="Bus 3 - Storage and Gas",
p_nom_extendable=True,
capital_cost=450.0, # Annualized CAPEX in $/MW
max_hours=4, # 4-hour storage duration
efficiency_store=0.92, # 92% charging efficiency
efficiency_dispatch=0.92, # 92% discharging efficiency
cyclic_state_of_charge=True
)
# 9. Solve Linear Optimal Power Flow with Linopy and HiGHS solver
status, condition = network.optimize(solver_name="highs")
print(f"Optimization Status: {status} | Termination Condition: {condition}")
# 10. Extract optimal capacities and nodal prices
print(f"Optimal Wind Capacity: {network.generators.at['Offshore Wind', 'p_nom_opt']:.2f} MW")
print(f"Optimal Battery Capacity: {network.storage_units.at['Grid Battery', 'p_nom_opt']:.2f} MW")
print("Nodal Marginal Prices ($/MWh):")
print(network.buses_t.marginal_price)
In this workflow, setting p_nom_extendable=True instructs PyPSA to treat asset sizing as an optimization decision variable alongside dispatch. When network.optimize() executes, PyPSA automatically compiles the underlying Linopy optimization problem, transmits the matrix to the HiGHS solver, retrieves the dual variables (providing marginal electricity prices across each bus and snapshot), and updates the Network object with optimal asset capacities.
Common pitfalls and modeling misconceptions
When engineering teams and researchers first implement PyPSA in power system studies, several recurring technical misconceptions can compromise model fidelity or solver convergence:
- Confusing DC Power Flow with Direct Current Hardware: The linearized “DC power flow” formulation is an approximation for alternating current (AC) networks derived by linearizing trigonometric power flow equations. It does not mean the underlying transmission lines are physical direct current cables. Direct current infrastructure (such as HVDC subsea lines) should be modeled using
Linkcomponents, notLinecomponents with zero reactance. - Misunderstanding PyPSA’s Grid Scale vs. Distribution Solvers: PyPSA assumes balanced, three-phase transmission networks. It does not natively model single-phase unbalanced distribution feeders, lateral phase asymmetries, or neutral wire currents. Attempting to simulate low-voltage distribution grids in PyPSA without appropriate aggregation can yield misleading voltage estimates. For unbalanced low-voltage networks, pandapower or OpenDSS are specifically designed for phase-by-phase calculations.
- Overlooking Reactive Power and Voltage Stability: In highly stressed transmission grids with large shares of converter-interfaced renewables, voltage collapse is frequently triggered by insufficient local reactive power support. Because linearized DC-OPF neglects reactive power (Q) and voltage magnitudes (|V|), PyPSA dispatch results should be spot-checked against non-linear AC power flow simulations (using
network.pf()) to verify that transmission lines do not exceed voltage stability margins. - Unit Consistency Traps: PyPSA adopts MW for active power, MVar for reactive power, MWh for energy, and $/MW (or $/MWh) for cost parameters. Entering equipment capacities in kilowatts (kW) or battery storage in kilowatt-hours (kWh) without standardizing to megawatt units introduces orders-of-magnitude scaling errors into the optimization matrix.
- Solver Scalability and Memory Limits: Formulating full-year (8,760 hours) hourly capacity expansion models with hundreds of network nodes generates optimization problems containing tens of millions of non-zero constraint coefficients. Using open-source simplex solvers like GLPK on problems of this scale can result in excessive solve times or out-of-memory errors; modern interior-point or barrier solvers (such as HiGHS with interior-point options or commercial solvers like Gurobi) are recommended for continent-scale formulations.
Frequently asked questions
What is the primary difference between PyPSA and pandapower?
PyPSA is primarily engineered for multi-period capacity expansion planning, renewable energy integration, and sector coupling across regional and continental transmission grids using linearized DC optimal power flow. In contrast, pandapower specializes in detailed electrical distribution grid operations, three-phase unbalanced power flow, transformer tap regulation, and short-circuit calculations using non-linear AC Newton-Raphson solvers.
How does PyPSA model multi-sector energy coupling like hydrogen and district heat?
PyPSA models cross-sector coupling using multi-port Link components that connect distinct carrier buses with specified conversion efficiencies. For example, an electrolyzer connects an electricity bus to a hydrogen bus, while a combined heat and power unit or heat pump connects electrical and thermal buses simultaneously, allowing the solver to co-optimize heating, gas, and power infrastructure.
Which mathematical programming solvers work best with PyPSA?
PyPSA interfaces through Linopy with both open-source and commercial mathematical programming solvers. For open-source workflows, HiGHS provides state-of-the-art performance for linear (LP) and mixed-integer linear (MILP) models, while Cbc and GLPK handle smaller problems. For continent-scale models with millions of decision variables (such as PyPSA-Eur), commercial solvers like Gurobi, CPLEX, or FICO Xpress offer the fastest barrier and simplex execution times.
Does PyPSA support AC optimal power flow or only linearized DC power flow?
PyPSA supports both non-linear AC power flow and linearized DC power flow. For static simulation of a given network state without optimization, network.pf() calculates exact non-linear AC load flows using Newton-Raphson iterations. For multi-period optimization and capacity expansion, PyPSA defaults to linearized DC-OPF to maintain computational tractability and convexity.
How does PyPSA optimize energy storage capacity and charge-discharge cycles?
PyPSA optimizes energy storage by modeling hourly state-of-charge conservation constraints across time snapshots. The optimization balances capital investment costs against operational arbitrage value, accounting for round-trip efficiencies, standing storage standing losses, and cyclical boundary conditions across the modeling horizon.
Sources
- Brown, T., Hörsch, J., and Schlachtberger, D. (2018). PyPSA: Python for Power System Analysis. Journal of Open Research Software, 6(1), 4. https://openresearchsoftware.metajnl.com/articles/10.5334/jors.188 (Accessed 2026-11-16)
- PyPSA Project Documentation. PyPSA: Python for Power System Analysis Documentation. https://pypsa.readthedocs.io (Accessed 2026-11-16)
- Linopy Project Documentation. Linopy: Linear, Integer and Quadratic Optimization with Labeled Dimensions. https://linopy.readthedocs.io (Accessed 2026-11-16)
- Hörsch, J., Hofmann, F., Schlachtberger, D., and Brown, T. (2018). PyPSA-Eur: An open optimisation model of the European transmission system. Energy Strategy Reviews, 22, 207-215. https://doi.org/10.1016/j.esr.2018.08.012 (Accessed 2026-11-16)
- Thurner, L., Scheidler, A., Schäfer, F., et al. (2018). pandapower — an open-source python tool for convenient modeling, analysis, and optimization of electric power systems. IEEE Transactions on Power Systems, 33(6), 6510-6521. https://ieeexplore.ieee.org/document/8344496 (Accessed 2026-11-16)
- Pfenninger, S., and Keirstead, J. (2018). Comparing approaches to modelling energy systems over multi-scale spatial and temporal horizons. Environmental Modelling and Software, 106, 211-230. https://doi.org/10.1016/j.envsoft.2018.03.029 (Accessed 2026-11-16)
Data: Open-Source Power and Energy System Modeling Frameworks Comparison
Comparative technical specifications, mathematical power flow formulations, optimization engines, and sector-coupling capabilities across prominent open-source power and energy systems modeling frameworks, compiled from peer-reviewed software papers and official project documentation.
Period covered: 1997-2026. Coverage: Global.
| Framework Name | Primary Modeling Paradigm | Power Flow Physics Formulation | Multi-Carrier Sector Coupling | Optimization Backend Engine | Software License | Initial Release Year (year) |
|---|---|---|---|---|---|---|
| PyPSA | Multi-period capacity expansion planning and operational dispatch | Linearized DC power flow with cycle Kirchhoff constraints; non-linear AC Newton-Raphson | Native multi-port conversion links (heat, hydrogen, gas, transport) | Linopy and Pyomo | MIT License | 2018 |
| pandapower | Power system operational analysis, distribution grid calculations, and state estimation | Full non-linear AC Newton-Raphson and DC power flow; unbalanced three-phase networks | Limited (focused on electrical grids, transformers, and switches) | SciPy and custom solvers (Newton-Raphson, Optigraph) | BSD-3-Clause | 2018 |
| Calliope | Multi-scale energy system design and optimal capacity expansion | Transport model without electrical impedance or phase angles | Extensive (modular energy vectors across heat, gas, power, and fuels) | Pyomo | Apache-2.0 | 2016 |
| OSeMOSYS | Long-term regional and national energy system decarbonization pathways | Transport and commodity flow balance (no electrical transmission physics) | Comprehensive (macro-level energy supply and demand balances) | GNU MathProg, PuLP, and Pyomo | Apache-2.0 | 2011 |
| MATPOWER | Power flow, continuation power flow, and optimal power flow simulation | Full non-linear AC optimal power flow (interior point) and DC OPF | Limited to electrical transmission and generation assets | MATLAB and native MIPS interior-point solver | BSD-3-Clause | 1997 |
Sources
- PyPSA: Python for Power System Analysis (Brown et al., 2018) (accessed 2026-11-16)
- pandapower — an open-source python tool (Thurner et al., 2018) (accessed 2026-11-16)
- Calliope: a multi-scale energy systems modelling framework (Pfenninger and Keirstead, 2018) (accessed 2026-11-16)
- OSeMOSYS: The Open Source Energy Modelling System (Howells et al., 2011) (accessed 2026-11-16)
- MATPOWER: Steady-State Operations, Planning, and Analysis Tools (Zimmerman et al., 2011) (accessed 2026-11-16)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







