1. Settings


I recommend running this notebook in a conda environment, which can be created from the environment.yml file provided with this notebook.

Import Python libraries

In [1]:
# Python modules
import os
import shutil
import pandas as pd
from time import time
from datetime import date
import datetime

# Custom scripts
import scripts.download as download 
import scripts.read as read
import scripts.preprocess as preprocess
import scripts.demand as demand
import scripts.cop as cop
import scripts.write as write
import scripts.metadata as metadata

%load_ext autoreload
%autoreload 2
%matplotlib inline

Version and changes

In [2]:
version = '2022-02-22'
changes = 'Update and extension'

Make directories

In [3]:
home_path = os.path.realpath('.')

input_path = os.path.join(home_path, 'input')
interim_path = os.path.join(home_path, 'interim')
output_path = os.path.join(home_path, 'output', version)

for path in [input_path, interim_path, output_path]:
    os.makedirs(path, exist_ok=True)

Select geographical and temporal scope

In [4]:
all_countries = ['AT', 'BE', 'BG', 'CZ', 'CH', 'DE', 'DK', 
                 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HR', 
                 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'NL', 
                 'NO', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'] # available
countries = ["DE"]  # selected for calculation
In [5]:
year_start = 2008
year_end = 2019

Set ECMWF access key

In the following, this notebook downloads weather data from the ECMWF server. For accessing this server, follow the steps below:

  1. Register at https://apps.ecmwf.int/registration/.
  2. Login at https://apps.ecmwf.int/auth/login/.
  3. Retrieve your key at https://api.ecmwf.int/v1/key/.
  4. Enter your key and your e-mail below.

If you have already installed your ECMWF KEY, this step is skipped.

In [6]:
#if not os.path.isfile(os.path.join(os.environ["USERPROFILE"], ".ecmwfapirc")):
 #   os.environ["ECMWF_API_URL"] = "https://api.ecmwf.int/v1"
  #  os.environ["ECMWF_API_KEY"] = "XXXXXXXXX"
   # os.environ["ECMWF_API_EMAIL"] = "[email protected]"

2. Download

In the following, weather and population data is downloaded from the respective sources. For all years and countries, this takes around 45 minutes to run.

Note that standard load profile parameters from BGW/BDEW are already provided with in the input directory. Energy statistics can be downloaded from the JRC-IDEES and preprocessed with the Processing Notebook</li>

Weather data

As mentioned above, weather data is downloaded from ECMWF, more specifically form the ERA-5 archive (https://www.ecmwf.int/en/forecasts/datasets/reanalysis-datasets/era5). The following data is retrieved:

  • Wind: wind speed at 10 m above ground for heating seasons (October-April) in 1979-2017 in monthly resolution
  • Temperature: ambient air temperature at 2 m above ground and soil temperature (0-7cm below ground) for the selected years in hourly resolution

All data is downloaded for the whole of Europe. If some data already exists on your computer, this data will be skipped in the download process.

In [7]:
download.temperatures(input_path, year_start, year_end)
Download successful

Population data

As mentioned above, population data is downloaded from EUROSTAT.

In [8]:
Download successful

3. Preprocessing

Population and weather data is preprocessed. This takes around 10 minutes to run.

Re-mapping population data

The population data from Eurostat features a 1 km² grid, which country-by-country transformed to the 0.75 x 0.75° grid of the weather data in the following. Interim results are saved/loaded from disk.

In [9]:
mapped_population = preprocess.map_population(input_path, countries, interim_path)
/Users/Jarusch/Documents/Hertie/when2heat_europe/interim/population_DE already exists and is read from disk.
Plot of the re-mapped population data of DE (first selected country) for visual inspection:

Preparing weather data

The temporal resolution of wind data is changed as follows:

  • From monthly to the average of all heating periods from 1979 to 2016

To speed up the calculation, all weather data is filtered by the selected countries.

In [10]:
wind = preprocess.wind(input_path, mapped_population)
Plot of the wind averages for visual inspection:
In [11]:
temperature = preprocess.temperature(input_path, year_start, year_start, mapped_population) 

4. Heat demand time series

For all years and countries, the calculation of heat demand time series takes around 20 minutes to run.

Reference temperature

To capture the thermal inertia of buildings, the daily reference temperature is calculated as the weighted mean of the ambient air temperature of the actual and the three preceding days.

In [12]:
reference_temperature = demand.reference_temperature(temperature['air'])

Heating threshold temperature adjustment

Reference temperatures are adjusted by differences in the estimated national heating threshold (Kozarcanin et al. 2020) as compared to Germany.

In [13]:
heating_thresholds = read.heating_thresholds(input_path)
In [14]:
adjusted_temperature = demand.adjust_temperature(reference_temperature, heating_thresholds)

Daily demand

Daily demand factors are derived from the reference temperatures using profile functions as described in BDEW.

In [15]:
daily_parameters = read.daily_parameters(input_path)
In [16]:
daily_heat = demand.daily_heat(adjusted_temperature,
In [17]:
daily_water = demand.daily_water(adjusted_temperature,

Hourly demand

Hourly damand factors are calculated from the daily demand based on hourly factors from BGW.

In [18]:
hourly_parameters = read.hourly_parameters(input_path)
In [19]:
a = demand.hourly_heat(daily_heat,
/Users/Jarusch/Documents/Hertie/when2heat_europe/scripts/demand.py:134: FutureWarning: The 'lookup' method is deprecated and will beremoved in a future version.You can use DataFrame.melt and DataFrame.locas a substitute.
  slp[column] = parameters[building].lookup(times, classes.loc[:, column])
In [20]:
hourly_heat = demand.hourly_heat(daily_heat,
In [21]:
hourly_water = demand.hourly_water(daily_water,
In [22]:
hourly_space = (hourly_heat - hourly_water).clip(lower=0)

Weight and scale

The spatial time series are weighted with the population and normalized to 1 TWh yearly demand each. For years included in the JRC-IDEES, time series are scaled according to the there reported annual values. The time series are not yet spatially aggregated because spatial time series are needed for COP calculation. To generate these annual heat demands use our Processing Notebook</li>

In [23]:
building_database = read.building_database(input_path)
In [24]:
spatial_space = demand.finishing(hourly_space, mapped_population, building_database['space'])
In [25]:
spatial_water = demand.finishing(hourly_water, mapped_population, building_database['water'])


The following cells can be used to save and reload the spatial hourly time series.

In [26]:
spatial_space.to_pickle(os.path.join(interim_path, 'spatial_space'))
spatial_water.to_pickle(os.path.join(interim_path, 'spatial_water'))
In [27]:
spatial_space = pd.read_pickle(os.path.join(interim_path, 'spatial_space'))[countries]
spatial_water = pd.read_pickle(os.path.join(interim_path, 'spatial_water'))[countries]

Aggregate and combine

All heat demand time series are aggregated country-wise and combined into one data frame.

In [28]:
final_heat = demand.combine(spatial_space, spatial_water)

5. COP time series

For all years and countries, the calculation of the coefficient of performance (COP) of heat pumps takes around 5 minutes to run.

Source temperature

For air-sourced, ground-sources and groundwater-sourced heat pumps (ASHP, GSHP and WSHP), the relevant heat source temperatures are calculated.

In [29]:
source_temperature = cop.source_temperature(temperature)

Sink temperatures

Heat sink temperatures, i.e. the temperature level at which the heat pumps have to provide heat, are calculated for floor heating, radiator heating and warm water.

In [30]:
sink_temperature = cop.sink_temperature(temperature)


The COP is derived from the temperature difference between heat sources and sinks using COP curves.

In [31]:
cop_parameters = read.cop_parameters(input_path)
In [32]:
spatial_cop = cop.spatial_cop(source_temperature, sink_temperature, cop_parameters)


The following cells can be used to save and reload the spatial hourly time series.

In [33]:
spatial_cop.to_pickle(os.path.join(interim_path, 'spatial_cop'))
In [34]:
spatial_cop = pd.read_pickle(os.path.join(interim_path, 'spatial_cop'))[countries]

Aggregating and correction

The spatial COP time series are weighted with the spatial heat demand and aggregated into national time series. The national time series are corrected for part-load losses.

In [35]:
final_cop = cop.finishing(spatial_cop, spatial_space, spatial_water)

COP averages

COP averages (performance factors) are calculated and saved to disk for validation purposes.

In [36]:
#cop.validation(final_cop, final_heat, interim_path, 'corrected')
In [37]:
#cop.validation(cop.finishing(spatial_cop, spatial_space, spatial_water, correction=1),
               #final_heat, interim_path, "uncorrected")

6. Writing

For data and metadata, this takes around 5 minutes to run.


As for the OPSD "Time Series" package, data are provided in three different "shapes":

  • SingleIndex (easy to read for humans, compatible with datapackage standard, small file size)
    • Fileformat: CSV, SQLite
  • MultiIndex (easy to read into GAMS, not compatible with datapackage standard, small file size)
    • Fileformat: CSV, Excel
  • Stacked (compatible with data package standard, large file size, many rows, too many for Excel)
    • Fileformat: CSV

The different shapes are created before they are saved to files.

In [38]:
shaped_dfs = write.shaping(final_heat, final_cop)

Write data to an SQL-database, ...

In [39]:
write.to_sql(shaped_dfs, output_path, home_path)

and to CSV.

In [40]:
write.to_csv(shaped_dfs, output_path)

Writing to Excel takes extremely long. As a workaround, a copy of the multi-indexed data is writtten to CSV and manually converted to Excel.


The metadata is reported in a JSON file.

In [44]:
metadata.make_json(shaped_dfs, version, changes, year_start, year_end, output_path)

Copy input data

In [ ]:
shutil.copytree(input_path, os.path.join(output_path, 'original_data'))


In [43]:
metadata.checksums(output_path, home_path)
In [ ]: