Post · 14 min read· pp. 523–536

Transformers

This example illustrates the use of transformers with non-trivial phase shift and tap ratio. The example is a copy of the pandapower minimal example.

In [2]:

Copied! diagram

ipynb
import numpy as np
import pandas as pd

import pypsa

n = pypsa.Network()

n.add("Bus", "MV bus", v_nom=20, v_mag_pu_set=1.02)
n.add("Bus", "LV1 bus", v_nom=0.4)
n.add("Bus", "LV2 bus", v_nom=0.4)

n.add(
    "Transformer",
    "MV-LV trafo",
    type="0.4 MVA 20/0.4 kV",
    bus0="MV bus",
    bus1="LV1 bus",
)
n.add(
    "Line", "LV cable", type="NAYY 4x50 SE", bus0="LV1 bus", bus1="LV2 bus", length=0.1
)
n.add("Generator", "External Grid", bus="MV bus", control="Slack", marginal_cost=10)
n.add("Load", "LV load", bus="LV2 bus", p_set=0.1, q_set=0.05);

import numpy as np import pandas as pd import pypsa n = pypsa.Network() n.add("Bus", "MV bus", v_nom=20, v_mag_pu_set=1.02) n.add("Bus", "LV1 bus", v_nom=0.4) n.add("Bus", "LV2 bus", v_nom=0.4) n.add( "Transformer", "MV-LV trafo", type="0.4 MVA 20/0.4 kV", bus0="MV bus", bus1="LV1 bus", ) n.add( "Line", "LV cable", type="NAYY 4x50 SE", bus0="LV1 bus", bus1="LV2 bus", length=0.1 ) n.add("Generator", "External Grid", bus="MV bus", control="Slack", marginal_cost=10) n.add("Load", "LV load", bus="LV2 bus", p_set=0.1, q_set=0.05);

text
/tmp/ipykernel_9087/2870386227.py:6: PyPSA2Warning: pandas reads strings as `str` dtype since 3.0. PyPSA converts them back to object dtype on import, but keeps `str` from PyPSA 2.0 on. Set `pypsa.options.future.string_dtype` to True to opt in now or to False to keep the current behaviour.
  n = pypsa.Network()

In [3]:

Copied! diagram

ipynb
def run_power_flow(n: pypsa.Network) -> pd.DataFrame:
    n.lpf()
    n.pf(use_seed=True)
    return pd.DataFrame(
        {
            "Voltage Angles": n.buses_t.v_ang.loc["now"] * 180.0 / np.pi,
            "Voltage Magnitude": n.buses_t.v_mag_pu.loc["now"],
        }
    )

def run_power_flow(n: pypsa.Network) -> pd.DataFrame: n.lpf() n.pf(use_seed=True) return pd.DataFrame( { "Voltage Angles": n.buses_t.v_ang.loc["now"] * 180.0 / np.pi, "Voltage Magnitude": n.buses_t.v_mag_pu.loc["now"], } )

In [4]:

Copied! diagram

ipynb
run_power_flow(n)

run_power_flow(n)

text
INFO:pypsa.network.power_flow:Performing linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x7379907296a0> for snapshot(s) Index(['now'], dtype='str', name='snapshot')
text
/tmp/ipykernel_9087/416371486.py:2: PyPSA2Warning: From PyPSA 2.0 on, `get_switchable_as_dense` returns columns in `inds` order, keeps duplicates and raises a `KeyError` for unknown names. Unique, known names in component order give the same result in both. Set `pypsa.options.future.inds_order` to True to opt in now or to False to keep the current behaviour.
  n.lpf()
INFO:pypsa.network.power_flow:Performing non-linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737922f8aad0> for snapshots Index(['now'], dtype='str', name='snapshot')

Out[4]:

Voltage AnglesVoltage Magnitude
name
MV bus0.0000001.020000
LV1 bus-150.7601261.008843
LV2 bus-149.8841410.964431

In [5]:

Copied! diagram

ipynb
n.transformers.tap_position = 2
run_power_flow(n)

n.transformers.tap_position = 2 run_power_flow(n)

text
INFO:pypsa.network.power_flow:Performing linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737922f8aad0> for snapshot(s) Index(['now'], dtype='str', name='snapshot')
text
INFO:pypsa.network.power_flow:Performing non-linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737922f71ba0> for snapshots Index(['now'], dtype='str', name='snapshot')

Out[5]:

Voltage AnglesVoltage Magnitude
name
MV bus0.0000001.020000
LV1 bus-150.8439110.959655
LV2 bus-149.8708370.912713

In [6]:

Copied! diagram

ipynb
n.transformers.tap_position = -2
run_power_flow(n)

n.transformers.tap_position = -2 run_power_flow(n)

text
INFO:pypsa.network.power_flow:Performing linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737922f71ba0> for snapshot(s) Index(['now'], dtype='str', name='snapshot')
text
INFO:pypsa.network.power_flow:Performing non-linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x73792230fd10> for snapshots Index(['now'], dtype='str', name='snapshot')

Out[6]:

Voltage AnglesVoltage Magnitude
name
MV bus0.0000001.020000
LV1 bus-150.6816661.063133
LV2 bus-149.8966341.021202

Now play with tap changer on LV side

In [7]:

Copied! diagram

ipynb
new_trafo_lv_tap = n.transformer_types.loc[["0.4 MVA 20/0.4 kV"]]
new_trafo_lv_tap.index = ["New trafo"]
new_trafo_lv_tap.tap_side = 1
new_trafo_lv_tap.T

new_trafo_lv_tap = n.transformer_types.loc[["0.4 MVA 20/0.4 kV"]] new_trafo_lv_tap.index = ["New trafo"] new_trafo_lv_tap.tap_side = 1 new_trafo_lv_tap.T

Out[7]:

New trafo
f_nom50.0
s_nom0.4
v_nom_020.0
v_nom_10.4
vsc6.0
vscr1.425
pfe1.35
i00.3375
phase_shift150.0
tap_side1
tap_neutral0
tap_min-2
tap_max2
tap_step2.5
referencespandapower;Oswald - Transformatoren - Vorlesun...

In [8]:

Copied! diagram

ipynb
n.add("TransformerType", "New trafo", **new_trafo_lv_tap.iloc[0].to_dict())
n.transformers.type = "New trafo"
n.transformers.tap_position = 2
run_power_flow(n)

n.add("TransformerType", "New trafo", **new_trafo_lv_tap.iloc[0].to_dict()) n.transformers.type = "New trafo" n.transformers.tap_position = 2 run_power_flow(n)

text
INFO:pypsa.network.power_flow:Performing linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737922f957b0> for snapshot(s) Index(['now'], dtype='str', name='snapshot')
text
INFO:pypsa.network.power_flow:Performing non-linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737922f957b0> for snapshots Index(['now'], dtype='str', name='snapshot')

Out[8]:

Voltage AnglesVoltage Magnitude
name
MV bus0.0000001.020000
LV1 bus-150.7558201.059317
LV2 bus-149.9648751.017221

In [9]:

Copied! diagram

ipynb
n.transformers.T

n.transformers.T

Out[9]:

nameMV-LV trafo
bus0MV bus
bus1LV1 bus
typeNew trafo
modelt
x0.058283
r0.01425
g0.003375
b-0.0
s_nom0.4
s_nom_mod0.0
s_nom_extendableFalse
s_nom_min0.0
s_nom_maxinf
s_nom_setNaN
s_max_pu1.0
capital_cost0.0
overnight_costNaN
discount_rateNaN
fom_cost0.0
num_parallel1.0
tap_ratio1.05
tap_side1
tap_position2
phase_shift150.0
phase_shift_min0.0
phase_shift_max0.0
activeTrue
build_year0
lifetimeinf
v_ang_min-inf
v_ang_maxinf
sub_network0
x_pu0.145712
r_pu0.035618
g_pu0.00135
b_pu-0.0
x_pu_eff0.152994
r_pu_eff0.037406
s_nom_opt0.0

In [10]:

Copied! diagram

ipynb
n.transformers.tap_position = -2
run_power_flow(n)

n.transformers.tap_position = -2 run_power_flow(n)

text
INFO:pypsa.network.power_flow:Performing linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x7379287d3350> for snapshot(s) Index(['now'], dtype='str', name='snapshot')
text
INFO:pypsa.network.power_flow:Performing non-linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737990903e50> for snapshots Index(['now'], dtype='str', name='snapshot')

Out[10]:

Voltage AnglesVoltage Magnitude
name
MV bus0.0000001.020000
LV1 bus-150.7652320.958366
LV2 bus-149.7893940.911353

Finally, consider the phase shift in the linear optimal power flow (n.optimize()). It solves a cycle-based linearised power flow, enforcing Kirchhoff's voltage law around the network's cycles. The radial network above has no cycle, so the phase shift cannot redistribute power and does not affect the optimised flows — it only offsets the absolute voltage angles seen in n.pf()/n.lpf(). The branch flows below are therefore unchanged by the phase shift:

In [11]:

Copied! diagram

ipynb
n.generators.p_nom = 1
n.lines.s_nom = 1
n.optimize()
pd.DataFrame(
    {
        "Active Power p0 (MW)": pd.concat(
            [n.lines_t.p0.loc["now"], n.transformers_t.p0.loc["now"]]
        )
    }
)

n.generators.p_nom = 1 n.lines.s_nom = 1 n.optimize() pd.DataFrame( { "Active Power p0 (MW)": pd.concat( [n.lines_t.p0.loc["now"], n.transformers_t.p0.loc["now"]] ) } )

text
/tmp/ipykernel_9087/981123384.py:3: PyPSA2Warning: From PyPSA 2.0 on, the objective leaves out the capital costs of existing capacity on extendable assets, which improves LP conditioning. Pass `include_objective_constant` to `n.optimize` to choose per call. Set `pypsa.options.future.exclude_objective_constant` to True to opt in now or to False to keep the current behaviour.
  n.optimize()
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['MV bus', 'LV1 bus', 'LV2 bus'], dtype='object', name='name')
text
WARNING:pypsa.consistency:Encountered nan's in varying data 'p' for columns ['External Grid'] of component 'Generator'.
text
WARNING:pypsa.consistency:The following lines have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['LV cable'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following sub_networks have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['0'], dtype='object', name='name')
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.04s
text
Set parameter WLSAccessID
text
Set parameter WLSSecret
text
Set parameter LicenseID to value 2537914
text
Academic license 2537914 - for non-commercial use only - registered to l.___@tu-berlin.de
text
Read LP format model from file /tmp/linopy-problem-ct6sus0m.lp
text
Reading time = 0.00 seconds
text
obj: 9 rows, 3 columns, 11 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 3 primals, 9 duals
Objective: 1.00e+00
Solver: gurobi
Runtime: 0.00s
Dual bound: 1.00e+00
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-fix-p-lower, Generator-fix-p-upper, Line-fix-s-lower, Line-fix-s-upper, Transformer-fix-s-lower, Transformer-fix-s-upper were not assigned to the network.

Out[11]:

Active Power p0 (MW)
name
LV cable0.1
MV-LV trafo0.1

Phase shift in a meshed network

To see the phase shift act through the optimisation we need a cycle. Below, two buses are joined by two parallel paths — an ordinary line and a phase-shifting transformer — with equal per-unit reactance. Without a phase shift the 50 MW load splits evenly between the two paths; a phase shift on the transformer drives a circulating flow around the cycle that redistributes the power. The optimisation now reproduces exactly what n.lpf() computes.

Note the input attribute is phase_shift; the realised/optimised shift is written back to the output n.transformers_t.phase_shift_opt.

In [12]:

Copied! diagram

ipynb
def meshed_network(phase_shift: float) -> pypsa.Network:
    m = pypsa.Network()
    m.add("Bus", ["A", "B"], v_nom=1.0)
    m.add("Generator", "gen", bus="A", control="Slack", p_nom=100, marginal_cost=10)
    m.add("Load", "load", bus="B", p_set=50)
    m.add("Line", "line", bus0="A", bus1="B", x=0.01, r=1e-6, s_nom=100)
    m.add(
        "Transformer",
        "PST",
        bus0="A",
        bus1="B",
        x=1.0,
        r=1e-6,
        s_nom=100,
        phase_shift=phase_shift,
    )
    return m


rows = []
for angle in [0.0, 5.0, 10.0]:
    opt = meshed_network(angle)
    opt.optimize()
    ref = meshed_network(angle)
    ref.lpf()
    rows.append(
        {
            "phase_shift (deg)": angle,
            "line p0 — optimize": opt.lines_t.p0.loc["now", "line"],
            "PST p0 — optimize": opt.transformers_t.p0.loc["now", "PST"],
            "line p0 — lpf": ref.lines_t.p0.loc["now", "line"],
            "PST p0 — lpf": ref.transformers_t.p0.loc["now", "PST"],
        }
    )
pd.DataFrame(rows).round(3)

def meshed_network(phase_shift: float) -> pypsa.Network: m = pypsa.Network() m.add("Bus", ["A", "B"], v_nom=1.0) m.add("Generator", "gen", bus="A", control="Slack", p_nom=100, marginal_cost=10) m.add("Load", "load", bus="B", p_set=50) m.add("Line", "line", bus0="A", bus1="B", x=0.01, r=1e-6, s_nom=100) m.add( "Transformer", "PST", bus0="A", bus1="B", x=1.0, r=1e-6, s_nom=100, phase_shift=phase_shift, ) return m rows = [] for angle in [0.0, 5.0, 10.0]: opt = meshed_network(angle) opt.optimize() ref = meshed_network(angle) ref.lpf() rows.append( { "phase_shift (deg)": angle, "line p0 — optimize": opt.lines_t.p0.loc["now", "line"], "PST p0 — optimize": opt.transformers_t.p0.loc["now", "PST"], "line p0 — lpf": ref.lines_t.p0.loc["now", "line"], "PST p0 — lpf": ref.transformers_t.p0.loc["now", "PST"], } ) pd.DataFrame(rows).round(3)

text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['A', 'B'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following lines have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['line'], dtype='object', name='name')
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.04s
text
Set parameter WLSAccessID
text
Set parameter WLSSecret
text
Set parameter LicenseID to value 2537914
text
Academic license 2537914 - for non-commercial use only - registered to l.___@tu-berlin.de
text
Read LP format model from file /tmp/linopy-problem-r6v1h1xq.lp
text
Reading time = 0.00 seconds
text
obj: 9 rows, 3 columns, 13 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 3 primals, 9 duals
Objective: 5.00e+02
Solver: gurobi
Runtime: 0.00s
Dual bound: 5.00e+02
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-fix-p-lower, Generator-fix-p-upper, Line-fix-s-lower, Line-fix-s-upper, Transformer-fix-s-lower, Transformer-fix-s-upper, Kirchhoff-Voltage-Law were not assigned to the network.
text
INFO:pypsa.network.power_flow:Performing linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737920fa3310> for snapshot(s) Index(['now'], dtype='str', name='snapshot')
text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['A', 'B'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following lines have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['line'], dtype='object', name='name')
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.03s
text
Set parameter WLSAccessID
text
Set parameter WLSSecret
text
Set parameter LicenseID to value 2537914
text
Academic license 2537914 - for non-commercial use only - registered to l.___@tu-berlin.de
text
Read LP format model from file /tmp/linopy-problem-vy63xb0a.lp
text
Reading time = 0.00 seconds
text
obj: 9 rows, 3 columns, 13 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 3 primals, 9 duals
Objective: 5.00e+02
Solver: gurobi
Runtime: 0.00s
Dual bound: 5.00e+02
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-fix-p-lower, Generator-fix-p-upper, Line-fix-s-lower, Line-fix-s-upper, Transformer-fix-s-lower, Transformer-fix-s-upper, Kirchhoff-Voltage-Law were not assigned to the network.
text
INFO:pypsa.network.power_flow:Performing linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737920fa3e70> for snapshot(s) Index(['now'], dtype='str', name='snapshot')
text
WARNING:pypsa.consistency:The following buses have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['A', 'B'], dtype='object', name='name')
text
WARNING:pypsa.consistency:The following lines have carriers which are not defined. Run n.sanitize() to add them. Components with undefined carriers:
Index(['line'], dtype='object', name='name')
text
INFO:linopy.model: Solve problem using Gurobi solver
text
INFO:linopy.model:Solver options:
 - log_to_console: False
text
INFO:linopy.io: Writing time: 0.04s
text
Set parameter WLSAccessID
text
Set parameter WLSSecret
text
Set parameter LicenseID to value 2537914
text
Academic license 2537914 - for non-commercial use only - registered to l.___@tu-berlin.de
text
Read LP format model from file /tmp/linopy-problem-mb8onihg.lp
text
Reading time = 0.00 seconds
text
obj: 9 rows, 3 columns, 13 nonzeros
text
Set parameter LogToConsole to value 0
text
INFO:linopy.constants: Optimization successful: 
Status: ok
Termination condition: optimal
Solution: 3 primals, 9 duals
Objective: 5.00e+02
Solver: gurobi
Runtime: 0.00s
Dual bound: 5.00e+02
Solver model: available
Solver message: 2
text
INFO:pypsa.optimization.optimize:The shadow-prices of the constraints Generator-fix-p-lower, Generator-fix-p-upper, Line-fix-s-lower, Line-fix-s-upper, Transformer-fix-s-lower, Transformer-fix-s-upper, Kirchhoff-Voltage-Law were not assigned to the network.
text
INFO:pypsa.network.power_flow:Performing linear load-flow on AC sub-network <pypsa.SubNetwork object at 0x737920fa1c50> for snapshot(s) Index(['now'], dtype='str', name='snapshot')

Out[12]:

phase_shift (deg)line p0 — optimizePST p0 — optimizeline p0 — lpfPST p0 — lpf
00.025.00025.00025.00025.000
15.029.36320.63729.36320.637
210.033.72716.27333.72716.273

A positive phase shift moves flow off the transformer onto the parallel line, and the optimisation and linear power flow agree to numerical precision.

diagram 2026-11-05

diagram 2020-02-28