Rung 6: KVL — passive lines under Kirchhoff's voltage law¶
One rung of the PyPSA corpus: the file pypsa.yaml projected onto what this network builds, attached to that network, and held to what PyPSA solves it to.
✔ Verified against pypsa 1.3.0 — objective 23962.0 on both sides; structure ≠
transmission_expansion_cost_limit2 vs 1+1 — one block per sense — ==, <=, >= — where PyPSA writes one row per labelled constraint whatever its sense;transmission_volume_expansion_limit2 vs 1+1 — one block per sense — ==, <=, >= — where PyPSA writes one row per labelled constraint whatever its sense; size ✔ 123 rows · ✔ 42 columns · ✔ 204 nonzeros; duals ✔ 123 rows; model for model: 19 blocks equal, 3 documented splits.
Rows and columns, PyPSA against specsolve, name for name
| row | PyPSA | specsolve |
|---|---|---|
Bus-nodal_balance |
20 | 20 |
Generator-fix-p-lower |
16 | 16 |
Generator-fix-p-upper |
16 | 16 |
Kirchhoff-Voltage-Law |
12 | 12 |
Line-ext-s-lower |
8 | 8 |
Line-ext-s-upper |
8 | 8 |
Line-ext-s_nom-lower |
2 | 2 |
Line-ext-s_nom-upper |
2 | 2 |
Line-fix-s-lower |
12 | 12 |
Line-fix-s-upper |
12 | 12 |
Line-s_nom_set |
1 | 1 |
Line-s_set |
1 | 1 |
Link-fix-p-lower |
4 | 4 |
Link-fix-p-upper |
4 | 4 |
tech_capacity_expansion_limit |
1 | 1 |
transmission_expansion_cost_limit |
2 | ≠ 1+1 |
transmission_volume_expansion_limit |
2 | ≠ 1+1 |
| column | PyPSA | specsolve |
|---|---|---|
Generator-p |
16 | 16 |
Line-s |
20 | 20 |
Line-s_nom |
2 | 2 |
Link-p |
4 | 4 |
The model¶
The same model, as math
The spec of the model a plain n.optimize() builds, in one file. Every declaration is named Component_attribute after the PyPSA statement it stands for, and each constraint's description opens with the linopy name PyPSA gives that row, so the two can be read side by side. PyPSA's regimes — extendable, committable — are data columns and become where: masks. Bounds are the explicit rows PyPSA writes, so their duals are row duals. Parameters no PyPSA table carries verbatim are computed in data prep and say so in their description.
Sets¶
| Symbol | Meaning |
|---|---|
| \(\mathcal{T}\) | index \(t\) — snapshot — dispatch periods |
| \(\mathcal{N}\) | index \(n\) — bus with \(\mathrm{Generator\_bus}: \mathcal{G} \to \mathcal{N},\ \mathrm{Link\_bus0}: \mathcal{L} \to \mathcal{N},\ \mathrm{Link\_output\_bus}: \mathcal{O} \to \mathcal{N},\ \mathrm{Load\_bus}: \mathcal{D} \to \mathcal{N},\ \mathrm{Line\_bus0}: \mathcal{K} \to \mathcal{N},\ \mathrm{Line\_bus1}: \mathcal{K} \to \mathcal{N}\) — network nodes |
| \(\mathcal{G}\) | index \(g\) — generator with \(\mathrm{Generator\_bus}: \mathcal{G} \to \mathcal{N}\) — generating units, each on one bus |
| \(\mathcal{L}\) | index \(l\) — link with \(\mathrm{Link\_bus0}: \mathcal{L} \to \mathcal{N},\ \mathrm{Link\_output\_link}: \mathcal{O} \to \mathcal{L}\) — controllable connections, each from one bus to the buses it delivers to |
| \(\mathcal{O}\) | index \(o\) — link_output with \(\mathrm{Link\_output\_link}: \mathcal{O} \to \mathcal{L},\ \mathrm{Link\_output\_bus}: \mathcal{O} \to \mathcal{N}\) — a link's output ports, one label per port a link declares — PyPSA's bus1, bus2, … columns read long, so a link of any number of output ports is one term in the balance, data prep |
| \(\mathcal{D}\) | index \(d\) — load with \(\mathrm{Load\_bus}: \mathcal{D} \to \mathcal{N}\) — demands, each on one bus |
| \(\mathcal{K}\) | index \(k\) — line with \(\mathrm{Line\_bus0}: \mathcal{K} \to \mathcal{N},\ \mathrm{Line\_bus1}: \mathcal{K} \to \mathcal{N}\) — passive branches, each between two buses, their flow set by impedance |
| \(\mathcal{C}\) | index \(c\) — cycle — independent cycles of the passive network graph — the cycle basis, data prep |
| \(\mathcal{B}\) | index \(b\) — global_constraint — PyPSA's GlobalConstraint rows, one label per declared limit |
Parameters¶
| Symbol | Meaning |
|---|---|
| \(\mathrm{w}\) | snapshot_weightings_objective over \(\mathcal{T}\) — PyPSA's snapshot_weightings.objective — hours a snapshot stands for in the cost |
| \(\mathrm{p}^{\mathrm{nom}}\) | Generator_p_nom over \(\mathcal{G}\) — nominal power |
| \(\mathrm{ext}\) | Generator_p_nom_extendable over \(\mathcal{G}\) — whether the nominal power is a decision |
| \(\underline{\mathrm{p}}\) | Generator_p_min_pu over \(\mathcal{T} \times \mathcal{G}\) — least output, per unit of nominal power |
| \(\overline{\mathrm{p}}\) | Generator_p_max_pu over \(\mathcal{T} \times \mathcal{G}\) — most output, per unit of nominal power — an availability profile |
| \(\mathrm{c}\) | Generator_marginal_cost over \(\mathcal{T} \times \mathcal{G}\) — cost of one unit of output |
| \(\mathrm{com}\) | Generator_committable over \(\mathcal{G}\) — whether output is gated by an on/off status decision |
| \(\mathrm{f}^{\mathrm{nom}}\) | Link_p_nom over \(\mathcal{L}\) — nominal power |
| \(\mathrm{ext}^{f}\) | Link_p_nom_extendable over \(\mathcal{L}\) — whether the nominal power is a decision |
| \(\underline{\mathrm{f}}\) | Link_p_min_pu over \(\mathcal{T} \times \mathcal{L}\) — least flow, per unit of nominal power — negative for a link that carries both ways |
| \(\overline{\mathrm{f}}\) | Link_p_max_pu over \(\mathcal{T} \times \mathcal{L}\) — most flow, per unit of nominal power |
| \(\eta\) | Link_efficiency over \(\mathcal{O}\) — share of the flow that arrives at an output port, PyPSA's efficiency, efficiency2, … read long — negative where that port consumes rather than delivers |
| \(\mathrm{d}^{f}\) | Link_output_delay over \(\mathcal{O}\) — snapshots a port's delivery lags its link's flow — PyPSA's delay, delay2, … read long, in snapshot_weightings.generators units, which the file states as whole snapshots; zero for a port that delivers at once |
| \(\mathrm{cyc}^{f}\) | Link_output_cyclic_delay over \(\mathcal{O}\) — whether a delayed port's flow wraps from the horizon's end — PyPSA's cyclic_delay, cyclic_delay2, …; where it does not, the flow still in transit at the first snapshots is lost |
| \(\mathrm{c}^{f}\) | Link_marginal_cost over \(\mathcal{T} \times \mathcal{L}\) — cost of one unit of flow |
| \(\mathrm{load}\) | Load_p_set over \(\mathcal{T} \times \mathcal{D}\) — demand |
| \(\mathrm{s}^{\mathrm{nom}}\) | Line_s_nom over \(\mathcal{K}\) — nominal apparent power |
| \(\mathrm{ext}^{s}\) | Line_s_nom_extendable over \(\mathcal{K}\) — whether the nominal apparent power is a decision |
| \(\overline{\mathrm{s}}\) | Line_s_max_pu over \(\mathcal{T} \times \mathcal{K}\) — most flow either way, per unit of nominal apparent power |
| \(\underline{\mathrm{s}}^{\mathrm{nom}}\) | Line_s_nom_min over \(\mathcal{K}\) — least nominal apparent power an extendable line may be built at |
| \(\overline{\mathrm{s}}^{\mathrm{nom}}\) | Line_s_nom_max over \(\mathcal{K}\) — most nominal apparent power an extendable line may be built at |
| \(\mathrm{c}^{\mathrm{cap},s}\) | Line_capital_cost over \(\mathcal{K}\) — cost of one unit of nominal apparent power — PyPSA's capital_cost, periodized as an annuity in data prep |
| \(\mathrm{s}^{\mathrm{nom,set}}\) | Line_s_nom_set over \(\mathcal{K}\) — a given nominal apparent power for an extendable line; one without a value has no row here |
| \(\mathrm{s}^{\mathrm{set}}\) | Line_s_set over \(\mathcal{T} \times \mathcal{K}\) — a given flow schedule; a line without one has no row here |
| \(\mathrm{x}\) | Line_cycle_weight over \(\mathcal{K} \times \mathcal{C}\) — the line's series impedance, signed by its orientation in the cycle — the cycle basis, data prep; a line in no cycle has no row |
| \(\mathrm{type}\) | GlobalConstraint_type over \(\mathcal{B}\) — which formula the row takes — primary_energy, operational_limit, transmission_volume_expansion_limit, transmission_expansion_cost_limit or tech_capacity_expansion_limit |
| \(\mathrm{sense}\) | GlobalConstraint_sense over \(\mathcal{B}\) — which way the row binds — <=, >= or == |
| \(\mathrm{K}\) | GlobalConstraint_constant over \(\mathcal{B}\) — the constant the total is held against; what a variable cannot carry — an initial charge, a non-extendable build — is folded in here by data prep |
| \(\mathrm{len}\) | Line_volume_weight over \(\mathcal{B} \times \mathcal{K}\) — the line's length where its carrier is in the row's set — data prep; a line outside it has no row |
| \(\mathrm{cc}\) | Line_expansion_cost_weight over \(\mathcal{B} \times \mathcal{K}\) — the line's capital cost where its carrier is in the row's set — data prep; a line outside it has no row |
| \(\mathrm{m}^{l}\) | Line_tech_capacity_weight over \(\mathcal{B} \times \mathcal{K}\) — one where the line is in the row's carrier-and-bus set — data prep; one outside it has no row |
Variables¶
| Symbol | Meaning |
|---|---|
| \(p\) | Generator_p over \(\mathcal{T} \times \mathcal{G}\) — Generator-p — output of a generator in a snapshot |
| \(f\) | Link_p over \(\mathcal{T} \times \mathcal{L}\) — Link-p — PyPSA's p0, the flow measured at the Link_bus0 end: a positive value withdraws there and injects at every bus the link's output ports deliver to |
| \(s\) | Line_s over \(\mathcal{T} \times \mathcal{K}\) — Line-s — PyPSA's p0, the flow measured at the Line_bus0 end: a positive value withdraws there and injects at Line_bus1, lossless |
| \(S\) | Line_s_nom_ext over \(\mathcal{K}\) — Line-s_nom — nominal apparent power where it is a decision; the parameter of the same PyPSA name carries the fixed regime |
Definitions¶
| Symbol | Meaning |
|---|---|
| \(\mathit{Link\_output\_arrival}\) | Link_output_arrival over \(\mathcal{T} \times \mathcal{O}\) — what a link delivers to an output port at a snapshot — its flow after the port's efficiency, delayed by the port's delay; where the port is cyclic_delay the delayed flow wraps from the horizon's end, and where it is not the flow still in transit at the first snapshots is lost. A port that does not delay (delay zero) delivers its flow unshifted, cyclic or not |
| \(\mathit{transmission\_volume\_expansion}\) | transmission_volume_expansion over \(\mathcal{B}\) — what a transmission_volume_expansion_limit row totals — length times the chosen build of the row's branches |
| \(\mathit{transmission\_expansion\_cost}\) | transmission_expansion_cost over \(\mathcal{B}\) — what a transmission_expansion_cost_limit row totals — capital cost times the chosen build of the row's branches |
| \(\mathit{tech\_capacity\_expansion}\) | tech_capacity_expansion over \(\mathcal{B}\) — what a tech_capacity_expansion_limit row totals — the chosen build of the row's carrier-and-bus set |
\(t \ominus k\) denotes cyclic translation: index \(t-k\) taken modulo the size of the dimension (roll). Plain \(t-k\) (shift) has no wraparound — terms translated past the edge are simply absent.
\(t \boxminus_{v} k\) denotes translation with \(v\) standing where index \(t-k\) leaves the dimension (shift(edge=v)), so the row at that boundary is built and carries \(v\) rather than being dropped.
Objective¶
Subject to¶
Generator_fix_p_lower
Generator_fix_p_upper
Link_fix_p_lower
Link_fix_p_upper
Line_fix_s_lower
Line_fix_s_upper
Line_ext_s_lower
Line_ext_s_upper
Line_ext_s_nom_lower
Line_ext_s_nom_upper
Line_s_nom_set
Line_s_set
Kirchhoff_Voltage_Law
GlobalConstraint_transmission_volume_expansion_limit_lb
GlobalConstraint_transmission_volume_expansion_limit_eq
GlobalConstraint_transmission_expansion_cost_limit_ub
GlobalConstraint_transmission_expansion_cost_limit_lb
GlobalConstraint_tech_capacity_expansion_limit_ub
Bus_nodal_balance
Definitions¶
Link_output_arrival
transmission_volume_expansion
transmission_expansion_cost
tech_capacity_expansion
Variable domains¶
Generator_p
Link_p
Line_s
Line_s_nom_ext
The spec, differential/pypsa/rungs/rung_06_kvl.yaml — the file projected onto what this rung builds:
description: The spec of the model a plain `n.optimize()` builds, in one file. Every declaration is named
`Component_attribute` after the PyPSA statement it stands for, and each constraint's description opens
with the linopy name PyPSA gives that row, so the two can be read side by side. PyPSA's regimes — extendable,
committable — are data columns and become `where:` masks. Bounds are the explicit rows PyPSA writes,
so their duals are row duals. Parameters no PyPSA table carries verbatim are computed in data prep and
say so in their description.
dimensions:
snapshot: {description: dispatch periods, dtype: datetime}
bus: {description: network nodes}
generator: {description: 'generating units, each on one bus'}
link: {description: 'controllable connections, each from one bus to the buses it delivers to'}
link_output: {description: 'a link''s output ports, one label per port a link declares — PyPSA''s `bus1`,
`bus2`, … columns read long, so a link of any number of output ports is one term in the balance,
data prep'}
load: {description: 'demands, each on one bus'}
line: {description: 'passive branches, each between two buses, their flow set by impedance'}
cycle: {description: 'independent cycles of the passive network graph — the cycle basis, data prep'}
global_constraint: {description: 'PyPSA''s `GlobalConstraint` rows, one label per declared limit'}
relations:
Generator_bus: {description: the bus a generator sits on, key: generator, values: bus}
Link_bus0: {description: the bus a link leaves, key: link, values: bus}
Link_output_link: {description: the link an output port belongs to, key: link_output, values: link}
Link_output_bus: {description: 'the bus an output port delivers to — PyPSA''s `bus1`, `bus2`, … columns.
A link of three output ports is three labels here rather than a third relation, so the file states
any number of them', key: link_output, values: bus}
Load_bus: {description: the bus a load sits on, key: load, values: bus}
Line_bus0: {description: the bus a line's flow is measured at, key: line, values: bus}
Line_bus1: {description: the bus at a line's other end, key: line, values: bus}
parameters:
snapshot_weightings_objective:
description: PyPSA's `snapshot_weightings.objective` — hours a snapshot stands for in the cost
dims: [snapshot]
Generator_p_nom:
description: nominal power
dims: [generator]
Generator_p_nom_extendable:
description: whether the nominal power is a decision
dims: [generator]
dtype: bool
Generator_p_min_pu:
description: least output, per unit of nominal power
dims: [snapshot, generator]
Generator_p_max_pu:
description: most output, per unit of nominal power — an availability profile
dims: [snapshot, generator]
Generator_marginal_cost:
description: cost of one unit of output
dims: [snapshot, generator]
Generator_committable:
description: whether output is gated by an on/off status decision
dims: [generator]
dtype: bool
Link_p_nom:
description: nominal power
dims: [link]
Link_p_nom_extendable:
description: whether the nominal power is a decision
dims: [link]
dtype: bool
Link_p_min_pu:
description: least flow, per unit of nominal power — negative for a link that carries both ways
dims: [snapshot, link]
Link_p_max_pu:
description: most flow, per unit of nominal power
dims: [snapshot, link]
Link_efficiency:
description: share of the flow that arrives at an output port, PyPSA's `efficiency`, `efficiency2`,
… read long — negative where that port consumes rather than delivers
dims: [link_output]
Link_output_delay:
description: snapshots a port's delivery lags its link's flow — PyPSA's `delay`, `delay2`, … read
long, in `snapshot_weightings.generators` units, which the file states as whole snapshots; zero
for a port that delivers at once
dims: [link_output]
dtype: int
Link_output_cyclic_delay:
description: whether a delayed port's flow wraps from the horizon's end — PyPSA's `cyclic_delay`,
`cyclic_delay2`, …; where it does not, the flow still in transit at the first snapshots is lost
dims: [link_output]
dtype: bool
Link_marginal_cost:
description: cost of one unit of flow
dims: [snapshot, link]
Load_p_set:
description: demand
dims: [snapshot, load]
Line_s_nom:
description: nominal apparent power
dims: [line]
Line_s_nom_extendable:
description: whether the nominal apparent power is a decision
dims: [line]
dtype: bool
Line_s_max_pu:
description: most flow either way, per unit of nominal apparent power
dims: [snapshot, line]
Line_s_nom_min:
description: least nominal apparent power an extendable line may be built at
dims: [line]
Line_s_nom_max:
description: most nominal apparent power an extendable line may be built at
dims: [line]
Line_capital_cost:
description: cost of one unit of nominal apparent power — PyPSA's `capital_cost`, periodized as an
annuity in data prep
dims: [line]
Line_s_nom_set:
description: a given nominal apparent power for an extendable line; one without a value has no row
here
dims: [line]
Line_s_set:
description: a given flow schedule; a line without one has no row here
dims: [snapshot, line]
Line_cycle_weight:
description: the line's series impedance, signed by its orientation in the cycle — the cycle basis,
data prep; a line in no cycle has no row
dims: [line, cycle]
GlobalConstraint_type:
description: which formula the row takes — `primary_energy`, `operational_limit`, `transmission_volume_expansion_limit`,
`transmission_expansion_cost_limit` or `tech_capacity_expansion_limit`
dims: [global_constraint]
dtype: str
GlobalConstraint_sense:
description: which way the row binds — `<=`, `>=` or `==`
dims: [global_constraint]
dtype: str
GlobalConstraint_constant:
description: the constant the total is held against; what a variable cannot carry — an initial charge,
a non-extendable build — is folded in here by data prep
dims: [global_constraint]
Line_volume_weight:
description: the line's length where its carrier is in the row's set — data prep; a line outside it
has no row
dims: [global_constraint, line]
Line_expansion_cost_weight:
description: the line's capital cost where its carrier is in the row's set — data prep; a line outside
it has no row
dims: [global_constraint, line]
Line_tech_capacity_weight:
description: one where the line is in the row's carrier-and-bus set — data prep; one outside it has
no row
dims: [global_constraint, line]
variables:
Generator_p:
description: '`Generator-p` — output of a generator in a snapshot'
dims: [snapshot, generator]
Link_p:
description: '`Link-p` — PyPSA''s `p0`, the flow measured at the `Link_bus0` end: a positive value
withdraws there and injects at every bus the link''s output ports deliver to'
dims: [snapshot, link]
Line_s:
description: '`Line-s` — PyPSA''s `p0`, the flow measured at the `Line_bus0` end: a positive value
withdraws there and injects at `Line_bus1`, lossless'
dims: [snapshot, line]
Line_s_nom_ext:
description: '`Line-s_nom` — nominal apparent power where it is a decision; the parameter of the same
PyPSA name carries the fixed regime'
dims: [line]
where: Line_s_nom_extendable
constraints:
Generator_fix_p_lower:
description: '`Generator-fix-p-lower` — a fixed generator outputs at least its minimum'
dims: [snapshot, generator]
where: not Generator_p_nom_extendable AND not Generator_committable
expression: Generator_p >= Generator_p_min_pu * Generator_p_nom
Generator_fix_p_upper:
description: '`Generator-fix-p-upper` — a fixed generator outputs at most what is available'
dims: [snapshot, generator]
where: not Generator_p_nom_extendable AND not Generator_committable
expression: Generator_p <= Generator_p_max_pu * Generator_p_nom
Link_fix_p_lower:
description: '`Link-fix-p-lower` — a fixed link carries at least its minimum, negative for the other
way'
dims: [snapshot, link]
where: not Link_p_nom_extendable
expression: Link_p >= Link_p_min_pu * Link_p_nom
Link_fix_p_upper:
description: '`Link-fix-p-upper` — a fixed link carries at most its nominal power'
dims: [snapshot, link]
where: not Link_p_nom_extendable
expression: Link_p <= Link_p_max_pu * Link_p_nom
Line_fix_s_lower:
description: '`Line-fix-s-lower` — a fixed line carries at least the negative of its rating'
dims: [snapshot, line]
where: not Line_s_nom_extendable
expression: Line_s >= -Line_s_max_pu * Line_s_nom
Line_fix_s_upper:
description: '`Line-fix-s-upper` — a fixed line carries at most its rating'
dims: [snapshot, line]
where: not Line_s_nom_extendable
expression: Line_s <= Line_s_max_pu * Line_s_nom
Line_ext_s_lower:
description: '`Line-ext-s-lower` — an extendable line carries at least the negative of its rating
of the chosen build'
dims: [snapshot, line]
where: Line_s_nom_extendable
expression: Line_s >= -Line_s_max_pu * Line_s_nom_ext
Line_ext_s_upper:
description: '`Line-ext-s-upper` — an extendable line carries at most its rating of the chosen build'
dims: [snapshot, line]
where: Line_s_nom_extendable
expression: Line_s <= Line_s_max_pu * Line_s_nom_ext
Line_ext_s_nom_lower:
description: '`Line-ext-s_nom-lower` — the chosen build is at least its floor'
dims: [line]
where: Line_s_nom_extendable
expression: Line_s_nom_ext >= Line_s_nom_min
Line_ext_s_nom_upper:
description: '`Line-ext-s_nom-upper` — the chosen build is at most its cap; a cap of infinity is no
row'
dims: [line]
where: Line_s_nom_extendable AND Line_s_nom_max
expression: Line_s_nom_ext <= Line_s_nom_max
Line_s_nom_set:
description: '`Line-s_nom_set` — the chosen build pinned, wherever a value is given'
dims: [line]
where: Line_s_nom_extendable AND Line_s_nom_set
expression: Line_s_nom_ext == Line_s_nom_set
Line_s_set:
description: '`Line-s_set` — flow pinned to the given schedule, wherever one is given'
dims: [snapshot, line]
where: Line_s_set
expression: Line_s == Line_s_set
Kirchhoff_Voltage_Law:
description: '`Kirchhoff-Voltage-Law` — around every independent cycle the impedance-weighted flows
sum to nothing, which is what makes the linear power flow physical rather than transport'
dims: [snapshot, cycle]
expression: sum(Line_s * Line_cycle_weight, over=line) == 0
GlobalConstraint_transmission_volume_expansion_limit_lb:
description: '`transmission_volume_expansion_limit` — its total, at least its constant'
dims: [global_constraint]
where: GlobalConstraint_type == 'transmission_volume_expansion_limit' AND GlobalConstraint_sense ==
'>='
expression: transmission_volume_expansion >= GlobalConstraint_constant
GlobalConstraint_transmission_volume_expansion_limit_eq:
description: '`transmission_volume_expansion_limit` — its total, at its constant'
dims: [global_constraint]
where: GlobalConstraint_type == 'transmission_volume_expansion_limit' AND GlobalConstraint_sense ==
'=='
expression: transmission_volume_expansion == GlobalConstraint_constant
GlobalConstraint_transmission_expansion_cost_limit_ub:
description: '`transmission_expansion_cost_limit` — its total, at most its constant'
dims: [global_constraint]
where: GlobalConstraint_type == 'transmission_expansion_cost_limit' AND GlobalConstraint_sense ==
'<='
expression: transmission_expansion_cost <= GlobalConstraint_constant
GlobalConstraint_transmission_expansion_cost_limit_lb:
description: '`transmission_expansion_cost_limit` — its total, at least its constant'
dims: [global_constraint]
where: GlobalConstraint_type == 'transmission_expansion_cost_limit' AND GlobalConstraint_sense ==
'>='
expression: transmission_expansion_cost >= GlobalConstraint_constant
GlobalConstraint_tech_capacity_expansion_limit_ub:
description: '`tech_capacity_expansion_limit` — its total, at most its constant'
dims: [global_constraint]
where: GlobalConstraint_type == 'tech_capacity_expansion_limit' AND GlobalConstraint_sense == '<='
expression: tech_capacity_expansion <= GlobalConstraint_constant
Bus_nodal_balance:
description: '`Bus-nodal_balance` — what is generated at a bus, storage dispatch and stores included,
less what the links take away, plus what arrives over them after losses and any delay at every port
they deliver to, meets the load there. A bus nothing is attached to has no row; PyPSA refuses one
that carries load, and this file does not yet.'
dims: [snapshot, bus]
expression: sum(Generator_p, by=Generator_bus, over=generator, into=bus) - sum(Link_p, by=Link_bus0,
over=link, into=bus) + sum(Link_output_arrival, by=Link_output_bus, over=link_output, into=bus)
- sum(Line_s, by=Line_bus0, over=line, into=bus) + sum(Line_s, by=Line_bus1, over=line, into=bus)
== sum(Load_p_set, by=Load_bus, over=load, into=bus)
expressions:
Link_output_arrival:
description: what a link delivers to an output port at a snapshot — its flow after the port's efficiency,
delayed by the port's `delay`; where the port is `cyclic_delay` the delayed flow wraps from the
horizon's end, and where it is not the flow still in transit at the first snapshots is lost. A port
that does not delay (`delay` zero) delivers its flow unshifted, cyclic or not
dims: [snapshot, link_output]
cases:
wrapping: {when: Link_output_cyclic_delay, expression: 'shift(at(Link_p, by=Link_output_link, over=link,
into=link_output) * Link_efficiency, along=snapshot, offset=Link_output_delay, edge=''wrap'')'}
otherwise: shift(at(Link_p, by=Link_output_link, over=link, into=link_output) * Link_efficiency, along=snapshot,
offset=Link_output_delay, edge=0)
transmission_volume_expansion: {description: what a `transmission_volume_expansion_limit` row totals
— length times the chosen build of the row's branches, expression: 'sum(Line_s_nom_ext * Line_volume_weight,
over=line)'}
transmission_expansion_cost: {description: what a `transmission_expansion_cost_limit` row totals — capital
cost times the chosen build of the row's branches, expression: 'sum(Line_s_nom_ext * Line_expansion_cost_weight,
over=line)'}
tech_capacity_expansion: {description: what a `tech_capacity_expansion_limit` row totals — the chosen
build of the row's carrier-and-bus set, expression: 'sum(Line_s_nom_ext * Line_tech_capacity_weight,
over=line)'}
objective: {sense: minimize, description: 'operating cost, each snapshot weighted by the hours it stands
for', expression: sum(Generator_p * Generator_marginal_cost * snapshot_weightings_objective) + sum(Link_p
* Link_marginal_cost * snapshot_weightings_objective) + sum(Line_s_nom_ext * Line_capital_cost)}
The prep — every table the spec declares, from the network — and the solve:
from differential.pypsa.prep import relation, static, varying, weighting
def _carrier_list(gc: pd.Series) -> list[str]:
return [c.strip().strip('[]()') for c in str(gc['carrier_attribute']).split(',')]
def _cycle_weights(n: pypsa.Network) -> pd.DataFrame:
"""The KVL rows PyPSA itself writes — ``n.cycle_matrix(apply_weights=True)``, reactance on AC and resistance on DC, times the 1e5 PyPSA scales every cycle row by for conditioning."""
n.determine_network_topology()
n.calculate_dependent_values()
cycles = n.cycle_matrix(apply_weights=True) * 1e5
rows = [
{'line': str(name), 'cycle': str(cycle), 'value': float(weight)}
for (kind, name), weights in cycles.iterrows()
for cycle, weight in weights.items()
if kind == 'Line' and weight
]
return pd.DataFrame(rows, columns=['line', 'cycle', 'value']).astype({'value': float})
def _emissions(n: pypsa.Network, gc: pd.Series) -> pd.Series:
"""The nonzero values of the carrier attribute a `primary_energy` row weighs."""
values = n.carriers[gc['carrier_attribute']]
return values[values != 0]
def _gc_constants(n: pypsa.Network) -> pd.DataFrame:
"""Each row's constant, net of the initial charge PyPSA folds into its side of the row.
A `primary_energy` or `operational_limit` row counts what its non-cyclic
storage draws down, so PyPSA adds the initial charge as a constant on the
variable side; the file keeps the variables and moves it here.
"""
rows = []
for label, gc in n.global_constraints.iterrows():
constant = float(gc['constant'])
if gc['type'] == 'primary_energy':
emissions = _emissions(n, gc)
sus = n.storage_units
member = sus['carrier'].isin(emissions.index) & ~sus['cyclic_state_of_charge']
constant -= float(
(sus.loc[member, 'carrier'].map(emissions) * sus.loc[member, 'state_of_charge_initial']).sum()
)
stores = n.stores
member = stores['carrier'].isin(emissions.index) & ~stores['e_cyclic']
constant -= float((stores.loc[member, 'carrier'].map(emissions) * stores.loc[member, 'e_initial']).sum())
if gc['type'] == 'operational_limit':
sus = n.storage_units
member = (sus['carrier'] == gc['carrier_attribute']) & ~sus['cyclic_state_of_charge']
constant -= float(sus.loc[member, 'state_of_charge_initial'].sum())
stores = n.stores
member = (stores['carrier'] == gc['carrier_attribute']) & ~stores['e_cyclic']
constant -= float(stores.loc[member, 'e_initial'].sum())
rows.append({'global_constraint': str(label), 'value': constant})
return pd.DataFrame(rows, columns=['global_constraint', 'value']).astype({'value': float})
def _in_tech_set(gc: pd.Series, component: pd.Series, nominal: str, bus: str) -> bool:
"""PyPSA's membership for a `tech_capacity_expansion_limit` row: extendable, the carrier, and the bus if named."""
at_bus = not gc.get('bus') or str(component[bus]) == str(gc['bus'])
return bool(component[f'{nominal}_extendable'] and component['carrier'] == gc['carrier_attribute'] and at_bus)
def _link_ports(n: pypsa.Network) -> pd.DataFrame:
"""A link's output ports read long — one row per port a link declares, carrying the link, the bus it delivers to and its efficiency.
PyPSA spells the ports across columns — ``bus1``/``efficiency``, ``bus2``/``efficiency2``, … — and a
link declares a port by naming a bus in one, so a link of any port count is as many rows here and
one term in the balance. The label is the link and the column the port came from.
"""
links = n.static('Link')
blank = pd.Series('', index=links.index, dtype=str)
frames = []
for port in ['1', *n.components.links.additional_ports]:
suffix = '' if port == '1' else port
buses = links.get(f'bus{port}', blank).astype(str)
# `efficiency`, `delay` and `cyclic_delay` are PyPSA's unsuffixed attributes: port 1
# spells them bare and every port after it takes the number
efficiencies = links.get(f'efficiency{suffix}', pd.Series(1.0, index=links.index)).astype(float)
delays = links.get(f'delay{suffix}', pd.Series(0, index=links.index)).fillna(0).astype(int)
cyclic = links.get(f'cyclic_delay{suffix}', pd.Series(False, index=links.index)).fillna(False).astype(bool)
frame = pd.DataFrame(
keyed(links.index, 'link')
| {
'bus': buses.to_numpy(),
'value': efficiencies.to_numpy(),
'delay': delays.to_numpy(),
'cyclic_delay': cyclic.to_numpy(),
'port': int(port),
}
)
frames.append(frame[buses.to_numpy() != ''])
ports = pd.concat(frames, ignore_index=True).sort_values(['link', 'port'], kind='stable')
ports['link_output'] = ports['link'] + '_bus' + ports['port'].astype(str)
return ports.drop(columns='port').reset_index(drop=True)
def _per_port(n: pypsa.Network, column: str, as_name: str | None = None) -> pd.DataFrame:
"""One column of the long port table keyed by ``link_output`` — what a port names, or what it carries.
*as_name* is what the file calls it: a relation keeps its target dimension's
own name, and every parameter over the ports lands under ``value``.
"""
ports = _link_ports(n)
keys = [key for key in ('scenario', 'link_output') if key in ports.columns]
return ports[[*keys, column]].rename(columns={column: as_name or column})
def _weights(gcs: pd.DataFrame, components: pd.DataFrame, dim: str, value) -> pd.DataFrame:
"""One row per (global constraint, member): *value* returns the weight, or 0/None outside the row's set."""
rows = [
{'global_constraint': str(label), dim: str(name), 'value': float(v)}
for label, gc in gcs.iterrows()
for name, component in components.iterrows()
if (v := value(gc, component))
]
return pd.DataFrame(rows, columns=['global_constraint', dim, 'value']).astype({'value': float})
n = build() # the network from the PyPSA tab
sources = {
'snapshot': pl.Series('snapshot', list(timesteps(n)), dtype=pl.Datetime('us')),
'bus': pl.Series('bus', list(names(n.buses.index).astype(str)), dtype=pl.String),
'generator': pl.Series('generator', list(names(generators.index).astype(str)), dtype=pl.String),
'link': pl.Series('link', list(names(links.index).astype(str)), dtype=pl.String),
'link_output': pl.Series('link_output', list(pd.unique(_link_ports(n)['link_output'])), dtype=pl.String),
'load': pl.Series('load', list(names(loads.index).astype(str)), dtype=pl.String),
'line': pl.Series('line', list(names(lines.index).astype(str)), dtype=pl.String),
'cycle': pl.Series('cycle', list(pd.unique(tables['Line_cycle_weight']['cycle'])), dtype=pl.String),
'global_constraint': pl.Series(
'global_constraint', list(names(n.global_constraints.index).astype(str)), dtype=pl.String
),
**scenarios(n),
**periods(n),
**carriers(n),
'Generator_bus': relation(n, 'Generator', 'bus'),
'Link_bus0': relation(n, 'Link', 'bus0'),
'Link_output_link': _per_port(n, 'link'),
'Link_output_bus': _per_port(n, 'bus'),
'Load_bus': relation(n, 'Load', 'bus'),
'Line_bus0': relation(n, 'Line', 'bus0'),
'Line_bus1': relation(n, 'Line', 'bus1'),
'snapshot_weightings_objective': weighting(n, 'objective'),
'Generator_p_nom': static(n, 'Generator', 'p_nom'),
'Generator_p_nom_extendable': static(n, 'Generator', 'p_nom_extendable'),
'Generator_p_min_pu': varying(n, 'Generator', 'p_min_pu'),
'Generator_p_max_pu': varying(n, 'Generator', 'p_max_pu'),
'Generator_marginal_cost': varying(n, 'Generator', 'marginal_cost'),
'Generator_committable': static(n, 'Generator', 'committable'),
'Link_p_nom': static(n, 'Link', 'p_nom'),
'Link_p_nom_extendable': static(n, 'Link', 'p_nom_extendable'),
'Link_p_min_pu': varying(n, 'Link', 'p_min_pu'),
'Link_p_max_pu': varying(n, 'Link', 'p_max_pu'),
'Link_efficiency': _per_port(n, 'value'),
'Link_output_delay': _per_port(n, 'delay', 'value'),
'Link_output_cyclic_delay': _per_port(n, 'cyclic_delay', 'value'),
'Link_marginal_cost': varying(n, 'Link', 'marginal_cost'),
'Load_p_set': varying(n, 'Load', 'p_set'),
'Line_s_nom': static(n, 'Line', 's_nom'),
'Line_s_nom_extendable': static(n, 'Line', 's_nom_extendable'),
'Line_s_max_pu': varying(n, 'Line', 's_max_pu'),
'Line_s_nom_min': static(n, 'Line', 's_nom_min'),
'Line_s_nom_max': static(n, 'Line', 's_nom_max'),
'Line_capital_cost': static(n, 'Line', 'capital_cost'),
'Line_s_nom_set': static(n, 'Line', 's_nom_set').dropna(),
'Line_s_set': varying(n, 'Line', 's_set').dropna(),
'Line_cycle_weight': _cycle_weights(n),
'GlobalConstraint_type': static(n, 'GlobalConstraint', 'type').astype({'value': str}),
'GlobalConstraint_sense': static(n, 'GlobalConstraint', 'sense').astype({'value': str}),
'GlobalConstraint_constant': _gc_constants(n),
'Line_volume_weight': _weights(
volume,
lines,
'line',
lambda gc, c: c['length'] if c['s_nom_extendable'] and c['carrier'] in _carrier_list(gc) else 0.0,
),
'Line_expansion_cost_weight': _weights(
expansion_cost,
lines,
'line',
lambda gc, c: c['capital_cost'] if c['s_nom_extendable'] and c['carrier'] in _carrier_list(gc) else 0.0,
),
'Line_tech_capacity_weight': _weights(
tech, lines, 'line', lambda gc, c: float(_in_tech_set(gc, c, 's_nom', 'bus0'))
),
}
with sps.solve('differential/pypsa/rungs/rung_06_kvl.yaml', sources) as solution:
solution.objective # 23962.0
The network, rung_06_kvl.py in the corpus — the spine plus what this rung adds:
"""Rung 6: KVL — passive lines under Kirchhoff's voltage law."""
from __future__ import annotations
from math import nan
import spine
def build():
"""The spine plus this rung's additions, as a ``pypsa.Network``."""
n = spine.build()
n.add('Bus', 'a')
n.add('Bus', 'b')
n.add('Bus', 'c')
n.add('Generator', 'hydro', bus='a', p_nom=80, marginal_cost=10)
n.add('Generator', 'diesel6', bus='b', p_nom=80, marginal_cost=50)
n.add('Load', 'town', bus='c', p_set=45)
n.add('Line', 'ab', bus0='a', bus1='b', carrier='AC', length=30, x=0.1, r=0.01, s_nom=60)
n.add('Line', 'bc', bus0='b', bus1='c', carrier='AC', length=40, x=0.2, r=0.01, s_nom=60, s_set=[16, nan, nan, nan])
n.add('Line', 'ca', bus0='c', bus1='a', carrier='AC', length=35, x=0.1, r=0.01, s_nom=60)
n.add(
'Line',
'ca2',
bus0='c',
bus1='a',
carrier='AC',
length=50,
x=0.15,
r=0.01,
s_nom_extendable=True,
capital_cost=10,
s_nom_max=40,
s_nom_set=30,
)
n.add(
'Line',
'ca3',
bus0='c',
bus1='a',
carrier='AC',
length=80,
x=0.12,
r=0.01,
s_nom_extendable=True,
capital_cost=8,
s_nom_max=40,
)
n.add(
'GlobalConstraint',
'vol_ac',
type='transmission_volume_expansion_limit',
carrier_attribute='AC',
sense='==',
constant=2300,
)
n.add(
'GlobalConstraint',
'vol_ac_floor',
type='transmission_volume_expansion_limit',
carrier_attribute='AC',
sense='>=',
constant=1000,
)
n.add(
'GlobalConstraint',
'cost_ac',
type='transmission_expansion_cost_limit',
carrier_attribute='AC',
sense='<=',
constant=500,
)
n.add(
'GlobalConstraint',
'cost_ac_floor',
type='transmission_expansion_cost_limit',
carrier_attribute='AC',
sense='>=',
constant=100,
)
n.add(
'GlobalConstraint',
'tech_ac',
type='tech_capacity_expansion_limit',
carrier_attribute='AC',
sense='<=',
constant=60,
)
return n
The data¶
The tables this rung is the first to declare (16), as the prep produced them:
Line_bus0.csv
Line_bus1.csv
Line_capital_cost.csv
Line_cycle_weight.csv
line,cycle,value
ab,0,10000.0
bc,0,20000.0
ca,0,10000.0
ca,1,10000.0
ca,2,10000.0
ca2,1,-15000.0
ca3,2,-12000.0
Line_expansion_cost_weight.csv
global_constraint,line,value
cost_ac,ca2,10.0
cost_ac,ca3,8.0
cost_ac_floor,ca2,10.0
cost_ac_floor,ca3,8.0
Line_s_max_pu.csv
snapshot,line,value
2015-01-01T00:00:00.000000,ab,1.0
2015-01-01T00:00:00.000000,bc,1.0
2015-01-01T00:00:00.000000,ca,1.0
2015-01-01T00:00:00.000000,ca2,1.0
2015-01-01T00:00:00.000000,ca3,1.0
2015-01-01T01:00:00.000000,ab,1.0
2015-01-01T01:00:00.000000,bc,1.0
2015-01-01T01:00:00.000000,ca,1.0
2015-01-01T01:00:00.000000,ca2,1.0
2015-01-01T01:00:00.000000,ca3,1.0
2015-01-01T02:00:00.000000,ab,1.0
2015-01-01T02:00:00.000000,bc,1.0
2015-01-01T02:00:00.000000,ca,1.0
2015-01-01T02:00:00.000000,ca2,1.0
2015-01-01T02:00:00.000000,ca3,1.0
2015-01-01T03:00:00.000000,ab,1.0
2015-01-01T03:00:00.000000,bc,1.0
2015-01-01T03:00:00.000000,ca,1.0
2015-01-01T03:00:00.000000,ca2,1.0
2015-01-01T03:00:00.000000,ca3,1.0
Line_s_nom.csv
Line_s_nom_extendable.csv
Line_s_nom_max.csv
Line_s_nom_min.csv
Line_s_nom_set.csv
Line_s_set.csv
Line_tech_capacity_weight.csv
Line_volume_weight.csv
global_constraint,line,value
vol_ac,ca2,50.0
vol_ac,ca3,80.0
vol_ac_floor,ca2,50.0
vol_ac_floor,ca3,80.0
cycle.csv
line.csv