LOPF then non-linear power flow with SciGRID

This Jupyter Notebook is also available to download at: http://www.pypsa.org/examples/scigrid-lopf-then-pf.ipynb and can be viewed as an HTML page at: http://pypsa.org/examples/scigrid-lopf-then-pf.html.

In this example, the dispatch of generators is optimised using the linear OPF, then a non-linear power flow is run on the resulting dispatch.

The data files for this example are in the examples folder of the github repository: https://github.com/PyPSA/PyPSA.

Data sources

The data is generated in a separate notebook at http://www.pypsa.org/examples/add_load_gen_trafos_to_scigrid.ipynb.

Grid: based on SciGRID Version 0.2 which is based on OpenStreetMap.

Load size and location: based on Landkreise (NUTS 3) GDP and population.

Load time series: from ENTSO-E hourly data, scaled up uniformly by factor 1.12 (a simplification of the methodology in Schumacher, Hirth (2015)).

Conventional power plant capacities and locations: BNetzA list.

Wind and solar capacities and locations: EEG Stammdaten, based on http://www.energymap.info/download.html, which represents capacities at the end of 2014. Units without PLZ are removed.

Wind and solar time series: REatlas, Andresen et al, "Validation of Danish wind time series from a new global renewable energy atlas for energy system analysis," Energy 93 (2015) 1074 - 1088.

NB:

All times in the dataset are UTC.

Where SciGRID nodes have been split into 220kV and 380kV substations, all load and generation is attached to the 220kV substation.

Warning

This dataset is ONLY intended to demonstrate the capabilities of PyPSA and is NOT (yet) accurate enough to be used for research purposes.

Known problems include:

i) Rough approximations have been made for missing grid data, e.g. 220kV-380kV transformers and connections between close sub-stations missing from OSM.

ii) There appears to be some unexpected congestion in parts of the network, which may mean for example that the load attachment method (by Voronoi cell overlap with Landkreise) isn't working, particularly in regions with a high density of substations.

iii) Attaching power plants to the nearest high voltage substation may not reflect reality.

iv) There is no proper n-1 security in the calculations - this can either be simulated with a blanket e.g. 70% reduction in thermal limits (as done here) or a proper security constrained OPF (see e.g. http://www.pypsa.org/examples/scigrid-sclopf.ipynb).

v) The borders and neighbouring countries are not represented.

vi) Hydroelectric power stations are not modelled accurately.

viii) The marginal costs are illustrative, not accurate.

ix) Only the first day of 2011 is in the github dataset, which is not representative. The full year of 2011 can be downloaded at http://www.pypsa.org/examples/scigrid-with-load-gen-trafos-2011.zip.

x) The ENTSO-E total load for Germany may not be scaled correctly; it is scaled up uniformly by factor 1.12 (a simplification of the methodology in Schumacher, Hirth (2015), which suggests monthly factors).

xi) Biomass from the EEG Stammdaten are not read in at the moment.

xii) Power plant start up costs, ramping limits/costs, minimum loading rates are not considered.

In [1]:
#make the code as Python 3 compatible as possible
from __future__ import print_function, division, absolute_import

import pypsa

import numpy as np

import pandas as pd

import os

import matplotlib.pyplot as plt

%matplotlib inline
In [2]:
#You may have to adjust this path to where 
#you downloaded the github repository
#https://github.com/PyPSA/PyPSA

csv_folder_name = os.path.dirname(pypsa.__file__) + "/../examples/scigrid-de/scigrid-with-load-gen-trafos/"

network = pypsa.Network(csv_folder_name=csv_folder_name)
INFO:pypsa.io:buses.csv found.
INFO:pypsa.io:No carriers.csv found.
INFO:pypsa.io:generators.csv found.
INFO:pypsa.io:lines.csv found.
INFO:pypsa.io:No line_types.csv found.
INFO:pypsa.io:No links.csv found.
INFO:pypsa.io:loads.csv found.
INFO:pypsa.io:No shunt_impedances.csv found.
INFO:pypsa.io:storage_units.csv found.
INFO:pypsa.io:No stores.csv found.
INFO:pypsa.io:transformers.csv found.
INFO:pypsa.io:No transformer_types.csv found.

Plot the distribution of the load and of generating tech

In [3]:
fig,ax = plt.subplots(1,1)

fig.set_size_inches(6,6)

load_distribution = network.loads_t.p_set.loc[network.snapshots[0]].groupby(network.loads.bus).sum()

network.plot(bus_sizes=0.5*load_distribution,ax=ax,title="Load distribution")
Out[3]:
(<matplotlib.collections.PathCollection at 0x7fed05d35b38>,
 <matplotlib.collections.LineCollection at 0x7fed05d455f8>)
In [4]:
fig.tight_layout()
#fig.savefig('load-distribution.png')
In [5]:
network.generators.groupby("carrier")["p_nom"].sum()
Out[5]:
carrier
Brown Coal       20879.500000
Gas              23913.130000
Geothermal          31.700000
Hard Coal        25312.600000
Multiple           152.700000
Nuclear          12068.000000
Oil               2710.200000
Other             3027.800000
Run of River      3999.100000
Solar            37041.524779
Storage Hydro     1445.000000
Waste             1645.900000
Wind Offshore     2973.500000
Wind Onshore     37339.895329
Name: p_nom, dtype: float64
In [6]:
network.storage_units.groupby("carrier")["p_nom"].sum()
Out[6]:
carrier
Pumped Hydro    9179.5
Name: p_nom, dtype: float64
In [7]:
techs = ["Gas","Brown Coal","Hard Coal","Wind Offshore","Wind Onshore","Solar"]

n_graphs = len(techs)

n_cols = 3

if n_graphs % n_cols == 0:
    n_rows = n_graphs // n_cols
else:
    n_rows = n_graphs // n_cols + 1

    
fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols)

size = 4

fig.set_size_inches(size*n_cols,size*n_rows)

for i,tech in enumerate(techs):
    i_row = i // n_cols
    i_col = i % n_cols
    
    ax = axes[i_row,i_col]
    
    gens = network.generators[network.generators.carrier == tech]
    
    gen_distribution = gens.groupby("bus").sum()["p_nom"].reindex(network.buses.index,fill_value=0.)
    
    network.plot(ax=ax,bus_sizes=0.2*gen_distribution)
    
    ax.set_title(tech)
    
    

Run Linear Optimal Power Flow on the first day of 2011

In [8]:
#to approximate n-1 security and allow room for reactive power flows,
#don't allow any line to be loaded above 70% of their thermal rating

contingency_factor = 0.7

network.lines.s_nom = contingency_factor*network.lines.s_nom
In [9]:
#There are some infeasibilities without small extensions                                                                                 
for line_name in ["316","527","602"]:
    network.lines.loc[line_name,"s_nom"] = 1200


#the lines to extend to resolve infeasibilities can
#be found by
#uncommenting the lines below to allow the network to be extended

#network.lines["s_nom_original"] = network.lines.s_nom

#network.lines.s_nom_extendable = True
#network.lines.s_nom_min = network.lines.s_nom

#Assume 450 EUR/MVA/km
#network.lines.capital_cost = 450*network.lines.length
In [10]:
group_size = 4

solver_name = "cbc"

print("Performing linear OPF for one day, {} snapshots at a time:".format(group_size))

network.storage_units.state_of_charge_initial = 0.

for i in range(int(24/group_size)):
    #set the initial state of charge based on previous round
    if i>0:
        network.storage_units.state_of_charge_initial = network.storage_units_t.state_of_charge.loc[network.snapshots[group_size*i-1]]
    network.lopf(network.snapshots[group_size*i:group_size*i+group_size],
                 solver_name=solver_name,
                 keep_files=True)
    network.lines.s_nom = network.lines.s_nom_opt
INFO:pypsa.pf:Slack bus for sub-network 0 is 1
INFO:pypsa.opf:Performed preliminary steps
INFO:pypsa.opf:Building pyomo model using `angles` formulation
Performing linear OPF for one day, 4 snapshots at a time:
INFO:pypsa.opf:Solving model using cbc
Solver log file: '/tmp/tmpa2tcgf6l.cbc.log'
Solver solution file: '/tmp/tmpq8pvko1h.pyomo.soln'
Solver problem files: ('/tmp/tmpq8pvko1h.pyomo.lp',)
INFO:pypsa.opf:Optimization successful
INFO:pypsa.pf:Slack bus for sub-network 0 is 1
INFO:pypsa.opf:Performed preliminary steps
INFO:pypsa.opf:Building pyomo model using `angles` formulation
INFO:pypsa.opf:Solving model using cbc
Solver log file: '/tmp/tmp1jvxhvsl.cbc.log'
Solver solution file: '/tmp/tmp8ejqzl1b.pyomo.soln'
Solver problem files: ('/tmp/tmp8ejqzl1b.pyomo.lp',)
INFO:pypsa.opf:Optimization successful
INFO:pypsa.pf:Slack bus for sub-network 0 is 1
INFO:pypsa.opf:Performed preliminary steps
INFO:pypsa.opf:Building pyomo model using `angles` formulation
INFO:pypsa.opf:Solving model using cbc
Solver log file: '/tmp/tmpjawb_0ek.cbc.log'
Solver solution file: '/tmp/tmps9cbruiy.pyomo.soln'
Solver problem files: ('/tmp/tmps9cbruiy.pyomo.lp',)
INFO:pypsa.opf:Optimization successful
INFO:pypsa.pf:Slack bus for sub-network 0 is 1
INFO:pypsa.opf:Performed preliminary steps
INFO:pypsa.opf:Building pyomo model using `angles` formulation
INFO:pypsa.opf:Solving model using cbc
Solver log file: '/tmp/tmpuv41kp72.cbc.log'
Solver solution file: '/tmp/tmpu94t0cff.pyomo.soln'
Solver problem files: ('/tmp/tmpu94t0cff.pyomo.lp',)
INFO:pypsa.opf:Optimization successful
INFO:pypsa.pf:Slack bus for sub-network 0 is 1
INFO:pypsa.opf:Performed preliminary steps
INFO:pypsa.opf:Building pyomo model using `angles` formulation
INFO:pypsa.opf:Solving model using cbc
Solver log file: '/tmp/tmp_1xt6zsu.cbc.log'
Solver solution file: '/tmp/tmp5ktiv_h4.pyomo.soln'
Solver problem files: ('/tmp/tmp5ktiv_h4.pyomo.lp',)
INFO:pypsa.opf:Optimization successful
INFO:pypsa.pf:Slack bus for sub-network 0 is 1
INFO:pypsa.opf:Performed preliminary steps
INFO:pypsa.opf:Building pyomo model using `angles` formulation
INFO:pypsa.opf:Solving model using cbc
Solver log file: '/tmp/tmp_w4v70hw.cbc.log'
Solver solution file: '/tmp/tmpuaqhhts4.pyomo.soln'
Solver problem files: ('/tmp/tmpuaqhhts4.pyomo.lp',)
INFO:pypsa.opf:Optimization successful
In [11]:
#if lines are extended, look at which ones are bigger
#network.lines[["s_nom_original","s_nom"]][abs(network.lines.s_nom - contingency_factor*network.lines.s_nom_original) > 1]
In [12]:
p_by_carrier = network.generators_t.p.groupby(network.generators.carrier, axis=1).sum()
In [13]:
p_by_carrier.drop((p_by_carrier.max()[p_by_carrier.max() < 1700.]).index,axis=1,inplace=True)
In [14]:
p_by_carrier.columns
Out[14]:
Index(['Brown Coal', 'Gas', 'Hard Coal', 'Nuclear', 'Run of River', 'Solar',
       'Wind Offshore', 'Wind Onshore'],
      dtype='object', name='carrier')
In [15]:
colors = {"Brown Coal" : "brown",
          "Hard Coal" : "k",
          "Nuclear" : "r",
          "Run of River" : "green",
          "Wind Onshore" : "blue",
          "Solar" : "yellow",
          "Wind Offshore" : "cyan",
          "Waste" : "orange",
          "Gas" : "orange"}
#reorder
cols = ["Nuclear","Run of River","Brown Coal","Hard Coal","Gas","Wind Offshore","Wind Onshore","Solar"]
p_by_carrier = p_by_carrier[cols]
In [16]:
fig,ax = plt.subplots(1,1)

fig.set_size_inches(12,6)

(p_by_carrier/1e3).plot(kind="area",ax=ax,linewidth=4,colors=[colors[col] for col in p_by_carrier.columns])


ax.legend(ncol=4,loc="upper left")

ax.set_ylabel("GW")

ax.set_xlabel("")
/home/tom/.virtualenvs/tom3/lib/python3.5/site-packages/pandas/tools/plotting.py:983: UserWarning: 'colors' is being deprecated. Please use 'color'instead of 'colors'
  warnings.warn(("'colors' is being deprecated. Please use 'color'"
Out[16]:
<matplotlib.text.Text at 0x7fecef1e26a0>