Custom Constraints#
PyPSA-USA formulates capacity-expansion and dispatch problems as linear (or mixed-integer) programs using PyPSA and linopy. The core formulation — the objective function, nodal energy balances, linearized power flow (KVL), storage consistency equations, and investment bounds — is inherited unchanged from PyPSA. It is documented in the PyPSA user guide on optimal power flow and is not re-derived here. This page documents only the constraints that PyPSA-USA adds on top of that formulation.
Custom constraints attach to the optimization model in two ways:
At solve time, through the
extra_functionalityhook ofn.optimize()implemented in solve_network.py. A registry maps{opts}wildcard tokens (RPS,REM,ERM,TCT) to constraint functions inworkflow/scripts/opts/; further constraints in the same hook are activated by configuration keys alone, or are always active.At network-preparation time, in prepare_network.py, where
{opts}tokens (Co2L,CH4L,Ep) and the{ll}wildcard are translated into PyPSAGlobalConstraintcomponents or cost adjustments before the model is built.
Wildcard tokens are parsed from the dash-separated {opts} string by
update_config_from_wildcards
and written into the run’s configuration, so every token has an equivalent config-file
setting. See the opts wildcard for the token reference table.
Notation#
Throughout this page, symbols follow PyPSA naming: \(p_{g,t}\) is the dispatch of
generator \(g\) in snapshot \(t\), \(P_g^{nom}\) the (extendable) nominal
capacity variable, \(p_g^{nom}\) a fixed nominal capacity, \(\bar{p}_{g,t}\) the
per-unit availability (p_max_pu), \(\eta\) a conversion efficiency, \(w_t\) the
snapshot weighting in hours, and \(d_{n,t}\) the exogenous load at bus \(n\).
Regions used by the policy constraints may be specified as state codes, ReEDS zones
(p1, p2, …), interconnect names, NERC region names, individual bus names, or all
(see get_region_buses in
opts/_helpers.py);
country and, where present, region bus attributes also match, and interconnect names
are compared lower-cased.
Overview#
Constraint |
What it enforces |
Trigger |
Source |
|---|---|---|---|
Minimum share of eligible generation relative to demand per region and horizon |
|
||
Cap on annual power-sector CO2 per region and horizon |
|
||
Energy-backed firm capacity above demand in every snapshot, per region |
|
||
Minimum/maximum nominal capacity per carrier group, region, and horizon |
|
||
Renewable capacity per carrier and land region bounded by developable potential |
always active |
||
Equal capacity expansion of paired forward/reverse links |
always active |
||
Shifted load bounded by a fixed share of nominal load per bus and snapshot |
|
||
Traded energy bounded by a share of demand per balancing period |
|
||
Aggregate MW cap on the total flow across a bundle of transmission paths |
|
||
System-wide CO2 cap via PyPSA |
|
||
Cap on annual gas-fired primary energy |
|
||
CO2 price added to marginal costs (objective, not a constraint) |
|
||
Bound on total line-volume or line-cost expansion |
|
||
Heat pumps, gas trade, water heating, EVs, sector CO2, sector DR |
sector studies ( |
Portfolio standards (RPS)#
Renewable Portfolio Standards (RPS) and Clean Energy Standards (CES) require a minimum share
of electricity to come from eligible carriers. Standards are enforced per Renewable Energy
Credit (REC) trading zone — states are mapped to their rec_trading_zone so that
in-zone REC trading is implicit — and per planning horizon. State-level targets are read
from electricity: portfolio_standards (CSV) and merged with ReEDS RPS and CES trajectories
supplied by the workflow. Eligible carriers default to
onwind, offwind, offwind_floating, solar, hydro, geothermal, biomass, EGS for RPS; CES
additionally includes nuclear, SMR, hydrogen_ct, CCGT-95CCS, CCGT-99CCS, Coal-95CCS.
Custom rows may specify any carrier group.
The REC trading zones over which portfolio standards are pooled. States in the same
tracking system (WREGIS, M-RETS, PJM-GATS, NEPOOL, …) share one constraint; states not
mapped to a system form a zone of their own. The mapping is
REC_TRADING_ZONE_MAPPER in workflow/scripts/constants.py, applied to each bus’s
reeds_state in build_base_network. Regenerate with snakemake docs_rec_trading_zones.#
Trigger: RPS token in {opts}. Like the other policy tokens it is skipped
when the network has no extendable generator (dispatch-only runs).
Targets are grouped by REC trading zone, planning horizon and the exact carrier string of
the row, so a custom row whose carrier list is spelled differently from the ReEDS default
forms its own constraint. The region column must be a single reeds_state code; rows
with any other region identifier are dropped. Only the states of a zone that carry a
positive target for that horizon and carrier group enter the constraint, on both sides:
for each zone \(Z\), horizon \(y\) and carrier group \(C\), let
\(Z' \subseteq Z\) be those states. Then:
Neither side carries snapshot weightings, so the constraint is a share of energy only
under uniform weightings. A zone/horizon/carrier group with no eligible generator is skipped
with a warning. In electricity-only studies the right-hand side is computed from the
exogenous load time series. In sector-coupled studies final electricity demand is
endogenous, so the requirement is instead applied against power-sector supply, pooled over
the zone: eligible generation (generators plus links feeding AC buses, weighted by their
static efficiency) must exceed \(\sum_{r \in Z'} \gamma_{r,y}\) times the supply from
carriers listed under conventional_carriers, renewable_carriers and
extendable_carriers: Generator in each state (add_RPS_constraints_sector).
Data sources and coverage are described on the policies page.
Regional emission limits (REM)#
Regional emission limits cap annual power-sector CO2 emissions for arbitrary bus regions
(states, ReEDS zones, interconnects, NERC regions, or all) and planning horizons. Limits
are read from the CSV at electricity: regional_Co2_limits with columns
name, regions, planning_horizon, limit (tonnes CO2); name becomes the constraint
name. Rows whose horizon is not an investment period, whose region matches no bus, or
whose region has no emitting generator are skipped silently.
Trigger: REM token in {opts}.
For each limit row with region set \(R\), horizon \(y\), and cap \(E_{R,y}\):
The atmosphere-store term applies only when the network tracks CO2 explicitly with a co2
carrier (sector networks). In sector-coupled studies the REM token instead dispatches
sector-specific CO2 constraints that allow different end-use sectors to decarbonize at
different rates; see sector emission targets.
Energy reserve margin (ERM)#
The ERM constraint requires each region to hold firm, deliverable capacity above its demand in every snapshot, not just at annual peak. Its distinguishing feature is that contributions must be energy-backed: storage and transmission contribute through a shadow (“reserve”) dispatch that must itself satisfy the full set of operational constraints — storage energy balance, dispatch bounds, and line/link ratings. This prevents storage from being credited for power it could not sustain and transmission from wheeling reserve that lines could not carry.
Trigger: ERM token in {opts}; margins configured under electricity: erm as
{region: margin} (default {'all': 0.15}).
For every region \(R\) with margin \(m_R\), auxiliary reserve variables are
added for storage units, lines and links, mirroring the real dispatch variables and subject
to the same bounds and storage energy balances (suffixed _RESERVES in the model). The
nodal reserve adequacy constraint is:
Generators are credited at their availability \(\bar{p}_{g,t}\), i.e. the capacity
factor of that snapshot. Only branches with both endpoints in \(R\) contribute —
reserve is shared within a region but not imported across its boundary. All terms are
activity-masked by build year and lifetime in multi-horizon
models. In planning horizons for which the electricity: regional_Co2_limits table has a
row with regions: all and limit: 0 (read whether or not REM is in {opts}),
carriers with positive CO2 intensity receive no capacity credit. A bus in \(R\) with
no extendable generator, storage unit or in-region branch — an empty left-hand side — and
a non-zero right-hand side raises an error rather than an infeasible model.
The dual of this constraint is stored per bus and snapshot as n.buses_t["erm_price"]
($/MW per snapshot) when solving with ERM, enabling capacity-price analysis.
Configuration details and valid region identifiers are documented in the opts wildcard section.
Technology capacity targets (TCT)#
TCT constraints impose minimum and/or maximum total nominal capacity for a carrier group in
a region and planning horizon — e.g. offshore-wind procurement mandates, nuclear retention,
or coal phase-outs. Targets are read from the CSV at
electricity: technology_capacity_targets with columns
name, planning_horizon, region, carrier, min, max (MW); min/max may be the keyword
existing to lock in currently installed capacity.
Trigger: TCT token in {opts}.
For each target row with region \(R\), carrier group \(C\), and horizon \(y\):
with whichever bound is present in the data. Because existing capacity enters the
right-hand side as a constant, a max below existing capacity cannot retire
non-extendable assets through the LP; in myopic runs, targets with max = 0 are instead
enforced by zeroing the affected non-extendable capacities before each horizon’s solve
(apply_forced_retirements).
The technology capacity targets shipped with the repo, by policy family: ReEDS nuclear
no-build (max = existing for nuclear, SMR, over both state and ReEDS-zone regions),
ReEDS forced retirements (max = 0 for the fossil and biomass carriers listed on each
state) and ReEDS storage mandates (an annual min MW trajectory of
4hr_battery_storage, shaded by the 2030 minimum). The map shows the shipped defaults
only — a study can point electricity: technology_capacity_targets at any other CSV with
the same columns. Regenerate with snakemake docs_tct_targets.#
Warning
TCT targets can only be used with renewable generators and utility-scale batteries in sector-coupled studies.
Land-use limits#
Renewable expansion is limited by developable land. Each extendable generator carries a
land_region attribute (assigned during clustering) and a p_nom_max potential derived
from the land-eligibility screens of the renewable-profile build. Because several
generator vintages or classes can share one resource area, capacity is constrained
jointly per carrier and land region rather than per generator. This constraint is always
active.
The maximum (rather than sum) on the first right-hand term reflects that all members of a
group share the same land-region potential. That potential is gross: it comes from the
land-eligibility screens of build_renewable_profiles and is never reduced by the plants
already standing on the site, so capacity that is not represented by a decision variable —
today’s brownfield plants, and under foresight: myopic every build frozen by
freeze_prior_periods — is subtracted from it. Activity is evaluated per investment period
from build_year/lifetime, and the term subtracted is the peak over the modelled
investment periods of the capacity active in that period: the constraint has no period
dimension, so it must hold for the worst period it spans, and a unit that has retired (or has
not yet been built) in a period releases its land there. A fixed unit with no build_year is
standing today and is always counted. For a myopic solve, which carries a single period, that
peak is simply the horizon being solved.
Extendable assets stay on the left-hand side, so no MW is charged to the land twice, and
a group whose existing capacity already exceeds its potential gets a right-hand side of
zero rather than a negative one.
With the {clusters} suffixes m/a/c, non-aggregated carriers keep their
pre-clustering bus as land_region, so land limits are enforced at {simpl} resolution
even when the transmission network is coarser.
Bidirectional link coupling#
Links that represent a single physical corridor in two directions (transport-model
transmission, H2 pipelines) are modeled as paired _fwd/_rev links. Names may also carry a
vintage, <name>_fwd_<year> / <name>_rev_<year> — the form add_itls gives the
future-horizon interface links — and pairing is within a vintage: <name>_fwd_2040 is
paired with <name>_rev_2040, never with <name>_rev_2030 or an unvintaged <name>_rev.
For each extendable pair, capacity expansion must be equal so both directions describe
the same asset:
This constraint is always active (it is a no-op when no paired extendable links exist). Note that ReEDS interface transfer limits (ITLs) are not a custom constraint: they enter the transport-model topology as link capacity ratings during clustering.
Demand-response capacity#
Price-responsive load shifting is modeled with paired storage buses and charger/discharger links added at every load bus (see the sector-coupling demand-response description for the storage-based implementation and its cost accounting — the power-sector version uses the same structure). The solve-time constraint caps how much load can be served from the demand-response buffer in any snapshot:
Trigger: electricity: demand_response: shift, a per-unit number. 0 (the
default) adds no demand-response components at all; values below 0.001 add the
components but no constraint. There is no “unbounded” setting — the schema declares
shift as a number, so the string inf is rejected at parse time.
In sector-coupled studies final demand is endogenous, so the bound is instead
\(\sum_{\ell \in D_n} p_{\ell,t} \leq s \sum_{\ell:\, bus0 = n} p_{\ell,t}\)
over the links leaving AC bus \(n\) toward the end-use sectors (carriers not ending in
-dr): demand-response delivery into a bus relative to all link flow leaving it. The
additional per-sector variants take shift in percent, not per unit — see the sector
list below.
Import and export volume limits#
When imports/exports to regions outside the model scope are enabled
(electricity: imports: enable / electricity: exports: enable), dedicated imports /
exports links are added at boundary buses. A volume constraint bounds traded energy per
balancing period (default monthly; day, week, month, or year):
Trigger: electricity: imports: volume_limit / electricity: exports: volume_limit,
a number in (0, 100] read as percent of demand, together with enable: true for that
direction; the balancing period is electricity: imports/exports: balancing_period. The
shipped default is inf, which adds no constraint. A value of 0 or an absent key is
skipped before the constraint function is reached and also adds no constraint, so a hard
zero-trade cap has to be expressed through capacity_limit or by disabling trade.
In sector studies demand is
measured as the flow into the end-use sectors, the bound becomes a linear constraint in
both trade and demand variables, and the share is rounded to two decimals
(12.5 % becomes 12 %).
Interface transmission limits#
A transmission interface is a bundle of paths between two groups of regions that is rated in
aggregate rather than path-by-path — CAISO’s simultaneous import capability being the canonical
example. Setting model_topology: interface_transmission_limits: true reads the interface table
at electricity: transmission_interface_limits (columns
interface, region_1, region_2, flow_12, flow_21) and adds one per-snapshot constraint per
interface and direction:
Trigger: model_topology: interface_transmission_limits: true.
\(I^{\rightarrow}\) and \(I^{\leftarrow}\) are selected by bus membership and carrier, never by link name.
Important
Only the imports / exports links added by add_extra_components are constrained, so the
limits are a no-op when electricity: imports and electricity: exports are both disabled.
A region_2 entry that is itself inside the modeled footprint contributes no trade links, so
internal AC lines between it and region_1 escape the cap. In the shipped
CAISO_Imports row this applies to p8, which is a California zone: in a California-only run
the internal p8-p9 corridor (~300 MW in the ReEDS/NARIS balancing-area table) is not
counted against the CAISO import cap, understating simultaneous imports by roughly that
corridor’s rating. This is documented, not corrected.
National emission cap (Co2L)#
Co2L in {opts} sets electricity: co2limit_enable: true and adds a standard PyPSA
GlobalConstraint (CO2Limit) on the co2_emissions carrier attribute:
It is a single PyPSA
primary_energy constraint over all snapshots of the model, not one per year: in a
perfect-foresight run with horizons 2030/2040/2050 it caps
\(10\,E_{2030} + 10\,E_{2040} + 1\,E_{2050} \leq \Omega \cdot n_{yr}\), and in a
myopic run each horizon \(y\) solved alone is capped at \(\Omega \cdot n_{yr} / k_y\).
Non-cyclic stores and storage units whose carrier has non-zero co2_emissions also enter
through their final energy level.
The token should always carry a numeric factor scaling a reference budget: Co2L0.05 sets
\(\Omega = 0.05 \times\) electricity: co2base. The constraint mechanics (including
the emission shadow price) are PyPSA’s; see the
PyPSA global-constraints documentation.
Note
co2base, co2limit, co2limit_enable, gaslimit and gaslimit_enable are optional keys
of the electricity: block (commented out in config.default.yaml). A Co2L<x> token
requires co2base and fails at parse time with a message naming it if it is unset
(#813); a bare Co2L only switches the
cap on and expects electricity: co2limit to be set directly. The same holds for CH4L
and gaslimit.
Natural gas limit (CH4L)#
CH4L sets electricity: gaslimit_enable: true and adds a GlobalConstraint (GasLimit)
on a gas_usage attribute assigned to the OCGT, CCGT, and CHP carriers, capping their
combined primary (thermal) energy use at electricity: gaslimit × \(n_{yr}\), with
the same cumulative, period-weighted form as Co2L above (one constraint over all
snapshots, weighted by \(k_y\)). The appended number gives the limit in TWh thermal:
CH4L200 sets 200 TWh thermal (always append a value — see the warning above). Only the
token route works today: gaslimit is written into the in-memory config after schema
validation, whereas setting it in a config file fails validation
(#813).
Emission pricing (Ep)#
Ep enables costs: emission_prices and is a cost adjustment rather than a constraint:
the CO2 price \(\pi\) (costs: emission_prices: co2, optionally given inline as e.g.
Ep50) is added to marginal costs of generators and storage units in proportion to their
emission intensity,
Note
The Ept token (time-varying monthly CO2 prices) sets
costs: emission_prices: co2_monthly_prices, but no workflow step currently consumes that
setting. Because Ept also matches the Ep parser, its net effect today is identical to
plain Ep: static emission pricing at the configured costs: emission_prices: co2 value.
Transmission expansion limits ({ll})#
The {ll} wildcard (handled in prepare_network, not {opts}) bounds total transmission
expansion with a PyPSA GlobalConstraint of type transmission_volume_expansion_limit
(v, MW·km) or transmission_expansion_cost_limit (c, $). The constraint bounds the
total length- or cost-weighted nominal capacity of all extendable AC lines and AC/DC
links, summed over every vintage, to factor times today’s value: v1.25 allows 25 %
more MW·km, not 125 %. Factors ≤ 1 (including the default v1.0) make nothing extendable
and add no binding constraint, so v0.8 is identical to v1.0; opt makes everything
extendable with no bound. In the ReEDS transport model each interface contributes its
forward and reverse links (each carrying half the interface capital cost) to both sides,
so the constant is twice the per-interface volume while the ratio is unaffected.
Warning
c<factor> is only consistent with a single investment period
(#815): PyPSA weights each extendable
asset’s cost by the sum of its active periods’ objective weightings, while the reference is
unweighted, so with several horizons the constraint is infeasible for any realistic
factor. Use v<factor> or opt in multi-period runs.
See the ll wildcard for the syntax and the PyPSA documentation for the formulation.
Temporal resolution (nH, nSEG)#
Temporal aggregation happens in prepare_network before the model is built. nH
(e.g. 3h) resamples all time series by averaging over every n hours within each
investment period, sums snapshot weightings accordingly, and rescales unit-commitment
parameters of committable generators (min_up_time/min_down_time from hours to
snapshots, ramp limits multiplied by n and clipped at 1). nSEG (e.g. 4380SEG)
applies tsam time-series segmentation
(an optional dependency, solved with the configured solver), choosing n variable-length
segments per investment period from all time-varying component attributes, each
normalised by its annual maximum. Each segment is represented by the first hour of the
segment, not the segment mean, weighted by the segment duration. Both write
clustering: temporal: resolution_elec, which can equivalently be set directly in the
config file.
Per-carrier adjustments#
The {opts} grammar also accepts <carrier>+{p,e,c,m}<factor> tokens (e.g.
solar+c0.5), parsed into adjustments: electricity: {p_nom_max | e_nom_max | capital_cost | marginal_cost}: {carrier: factor}.
Warning
These tokens are not usable (#814): no
config layer defines a top-level adjustments: key, so any + token raises
KeyError: 'adjustments' in every rule that carries {opts}; and even with the key
present no script applies adjustments: to the network. The mechanism is inherited from
PyPSA-Eur.
Sector-coupling constraints#
Sector-coupled studies ({sector} other than E) activate additional constraints in the
same extra_functionality hook. They are documented (with their data and schematics) on
the sector pages and are only listed here:
Sector CO2 targets — replaces the power-sector
REMconstraint with per-sector emission limits; see sector coupling and the sector configuration.Sector RPS — the endogenous-demand RPS variant described above.
Cooling heat-pump coupling — ties heat-pump cooling output to installed heating capacity; see the service-sector heat-pump docs.
GSHP capacity limit — bounds ground-source relative to air-source heat pumps by the rural/urban population ratio; only when
sector: service_sector: split_urban_ruralis false; see the heat-pump documentation.Natural-gas import/export limits — bounds gas trade with out-of-scope regions to ranges around historical volumes, per link and investment period; only when
sector: natural_gas: importsis set; upper bounds given asinfare skipped; see the natural-gas sector page.Water-heater storage — forces water-heating demand to be served through the storage buffer; only when
sector: service_sector: water_heating: simple_storageis false (the default is true, so it is off by default); see the service sector page.EV generation policy — caps electric-vehicle-served transport demand per mode and horizon as an unweighted sum over snapshots; only when
sector: transport_sector: ev_policyis non-empty; see the transportation sector page.Sector demand response — per-sector (and optionally per-carrier) shiftable-load bounds, with
shiftin percent (the power-sectorshiftis per unit); see demand response.Industrial fossil minimum — a floor on fossil-served industrial heat per state, unweighted; only when
sector: industrial_sector: min_fossil_generation(percent) exceeds 0.1; see the industrial sector page.