Time series: Processing Notebook
This Notebook is part of the Time series Data Package of Open Power System Data. |
This Notebook handles missing data, performs calculations and aggragations and creates the output files.
Executing this script till the end will create a new version of the data package.
The Version number specifies the local directory for the data
We include a note on what has been changed.
version = '2017-07-09'
changes = '''include ENTSO E transparency, RTE, APG'''
This section: load libraries and set up a log.
Note that the download module makes use of the pycountry library that is not part of Anaconda. Install it with with pip install pycountry
from the command line.
# Python modules
from datetime import datetime, date, timedelta, time
import pandas as pd
import numpy as np
import logging
import json
import sqlite3
import yaml
import itertools
import os
import pytz
import hashlib
from shutil import copyfile
# Skripts from time-series repository
from timeseries_scripts.read import read
from timeseries_scripts.download import download
from timeseries_scripts.imputation import find_nan
from timeseries_scripts.imputation import resample_markers
from timeseries_scripts.make_json import make_json
# Reload modules with execution of any code, to avoid having to restart
# the kernel after editing timeseries_scripts
%load_ext autoreload
%autoreload 2
# make sure the working directory is this file's directory
try:
os.chdir(home_path)
except NameError:
home_path = os.path.realpath('.')
sources_yaml_path = os.path.join(home_path, 'input', 'sources.yml')
areas_csv_path = os.path.join(home_path, 'input', 'areas.csv')
data_path = os.path.join('E:', os.sep, 'time series', version, 'original_data')
out_path = os.path.join('E:', os.sep, 'time series', version)
temp_path = os.path.join('E:', os.sep, 'time series', 'temp')
os.makedirs(out_path, exist_ok=True)
os.makedirs(temp_path, exist_ok=True)
# change to temp directory
os.chdir(temp_path)
os.getcwd()
FORMAT = '%(asctime)s %(levelname)s %(message)s'
DATEFORMAT = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(fmt=FORMAT, datefmt=DATEFORMAT)
logging.basicConfig(level=logging.INFO,
format=FORMAT,
datefmt=DATEFORMAT)
logfile = logging.FileHandler('log1.log')
logfile.setFormatter(formatter)
logfile.setLevel(logging.INFO)
logger = logging.getLogger(__name__)
logger.addHandler(logfile)
logger.setLevel(logging.INFO)
# For more detailed logging messages, replace 'INFO' with 'DEBUG'
# (May slow down computation).
This section: select the time range and the data sources for download and read. Default: all data sources implemented, full time range available.
Source parameters are specified in input/sources.yml, which describes, for each source, the datasets (such as wind and solar generation) alongside all the parameters necessary to execute the downloads.
The option to perform downloading and reading of subsets is for testing only. To be able to run the script succesfully until the end, all sources have to be included, or otherwise the script will run into errors (i.e. the step where aggregate German timeseries are caculated requires data from all four German TSOs to be loaded).
In order to do this, specify the beginning and end of the interval for which to attempt the download.
Type None
to download all available data.
start_from_user = date(2006, 1, 1)
end_from_user = date(2017, 5, 31)
Instead of downloading from the sources, the complete raw data can be downloaded as a zip file from the OPSD Server. Advantages are:
In order to do this, specify an archive version to use the raw data from that version that has been cached on the OPSD server as input. All data from that version will be downloaded - timerange and subset will be ignored.
Type None
to download directly from the original sources.
archive_version = None # i.e. '2016-07-14'
Optionally, specify a subset to download/read.
The next cell prints the available sources and datasets.
with open(sources_yaml_path, 'r') as f:
sources = yaml.load(f.read())
for k, v in sources.items():
print(yaml.dump({k: list(v.keys())}, default_flow_style=False))
Copy from its output and paste to following cell to get the right format.
Type subset = None
to include all data.
subset = yaml.load('''
insert_source_here:
- insert_dataset1_from_that_source_here
- insert_dataset2_here
more_sources:
- more_data_sets
''')
# need to exclude Elia data due to unclear copyright situation
exclude = yaml.load('''
- Elia
''')
subset = {}
subset = yaml.load('''
PSE:
- wind
''')
Now eliminate sources and variables not in subset.
with open(sources_yaml_path, 'r') as f:
sources = yaml.load(f.read())
if subset: # eliminate sources and variables not in subset
sources = {source_name: {k: v
for k, v in sources[source_name].items()
if k in variable_list}
for source_name, variable_list in subset.items()}
if exclude: # eliminate sources and variables in exclude
sources = {source_name: variable_dict
for source_name, variable_dict in sources.items()
if not source_name in exclude}
This section: download data. Takes about 1 hour to run for the complete data set (subset=None
).
First, a data directory is created on your local computer. Then, download parameters for each data source are defined, including the URL. These parameters are then turned into a YAML-string. Finally, the download is executed file by file.
Each file is saved under it's original filename. Note that the original file names are often not self-explanatory (called "data" or "January"). The files content is revealed by its place in the directory structure.
download(sources, data_path,
archive_version=archive_version,
start_from_user=start_from_user,
end_from_user=end_from_user)
Energinet.dk data needs to be downloaded manually here. The website seems as of 2017-07 to be only available in Danish.
Check The Boxes as specified below, then press the "Get extract"-button at the end of the page.
You will receive a file Market Data.xls
of about 50 MB. Open the file in Excel. There will be a warning from Excel saying that file extension and content are in conflict. Select "open anyways" and and save the file as .xlsx
. This will compress the file by ~80%, resulting in faster processing afterwards.
In order to be found by the read-function, place the downloaded file in the following subdirectory:
\original_data\Energinet.dk\prices_wind_solar\2005-01-01_2017-12-31\
Boxes to check:
This section: Read each downloaded file into a pandas-DataFrame and merge data from different sources if it has the same time resolution. Takes ~15 minutes to run.
Set the title of the rows at the top of the data used to store metadata internally. The order of this list determines the order of the levels in the resulting output.
headers = ['region', 'variable', 'attribute', 'source', 'web', 'unit']
Read a prepared table containing meta data on the geographical areas
areas = pd.read_csv(areas_csv_path)
View the areas table
areas.loc[areas['OPSD area'].notnull(),:'EIC'].fillna('')
Loop through sources and variables to do the reading. First read the originla CSV, Excel etc. files into pandas DataFrames.
areas = pd.read_csv(areas_csv_path)
# For each source in the source dictionary
for source_name, source_dict in sources.items():
# For each variable from source_name
for variable_name, param_dict in source_dict.items():
# variable_dir = os.path.join(data_path, source_name, variable_name)
res_list = param_dict['resolution']
url = param_dict['web']
for res_key in res_list:
df = read(data_path, areas, source_name, variable_name,
url, res_key, headers,
start_from_user=start_from_user,
end_from_user=end_from_user)
os.makedirs(res_key, exist_ok=True)
filename = '_'.join([source_name, variable_name]) + '.pickle'
df.to_pickle(os.path.join(res_key, filename))
Then combine the DataFrames that have the same temporal resolution
# Create a dictionary of empty DataFrames to be populated with data
data_sets = {'15min': pd.DataFrame(), '30min': pd.DataFrame(), '60min': pd.DataFrame()}
entso_e = {'15min': pd.DataFrame(), '30min': pd.DataFrame(), '60min': pd.DataFrame()}
for res_key in data_sets.keys():
for filename in os.listdir(res_key):
source_name = filename.split('_')[0]
if subset and not source_name in subset.keys():
continue
logger.info(filename)
df_portion = pd.read_pickle(os.path.join(res_key, filename))
if source_name == 'ENTSO-E Transparency FTP':
dfs = entso_e
else:
dfs = data_sets
if dfs[res_key].empty:
dfs[res_key] = df_portion
elif not df_portion.empty:
dfs[res_key] = dfs[res_key].combine_first(df_portion)
else:
logger.warning(filename + 'was empty')
for res_key, df in data_sets.items():
logger.info(res_key + ': %s', df.shape)
for res_key, df in entso_e.items():
logger.info(res_key + ': %s', df.shape)
Display some rows of the dataframes to get a first impression of the data.
data_sets['60min'].head()
Save the DataFrames created by the read function to disk. This way you have the raw data to fall back to if something goes wrong in the ramainder of this notebook without having to repeat the previos steps.
data_sets['15min'].to_pickle('raw_data_15.pickle')
data_sets['30min'].to_pickle('raw_data_30.pickle')
data_sets['60min'].to_pickle('raw_data_60.pickle')
entso_e['15min'].to_pickle('raw_entso_e_15.pickle')
entso_e['30min'].to_pickle('raw_entso_e_30.pickle')
entso_e['60min'].to_pickle('raw_entso_e_60.pickle')
Load the DataFrames saved above
data_sets = {}
data_sets['15min'] = pd.read_pickle('raw_data_15.pickle')
data_sets['30min'] = pd.read_pickle('raw_data_30.pickle')
data_sets['60min'] = pd.read_pickle('raw_data_60.pickle')
entso_e['15min'] = pd.read_pickle('raw_entso_e_15.pickle')
entso_e['30min'] = pd.read_pickle('raw_entso_e_30.pickle')
entso_e['60min'] = pd.read_pickle('raw_entso_e_60.pickle')
This section: missing data handling, aggregation of sub-national to national data, aggregate 15'-data to 60'-resolution. Takes 30 minutes to run.
Patch missing data. At this stage, only small gaps (up to 2 hours) are filled by linear interpolation. This catched most of the missing data due to daylight savings time transitions, while leaving bigger gaps untouched
The exact locations of missing data are stored in the nan_table
DataFrames.
Where data has been interpolated, it is marked in a new column comment
. For eaxample the comment solar_DE-transnetbw_generation;
means that in the original data, there is a gap in the solar generation timeseries from TransnetBW in the time period where the marker appears.
Patch the datasets and display the location of missing Data in the original data. Takes ~5 minutes to run.
nan_tables = {}
for res_key, df in data_sets.items():
data_sets[res_key], nan_tables[res_key] = find_nan(
df, res_key, headers, patch=True)
for res_key, df in entso_e.items():
entso_e[res_key], nan_tables[res_key + ' ENTSO-E'] = find_nan(
df, res_key, headers, patch=True)
Execute this to see an example of where the data has been patched.
data_sets['15min'][data_sets['15min']['interpolated_values'].notnull()].tail()
Display the table of regions of missing values
nan_tables['60min']
You can export the NaN-tables to Excel in order to inspect where there are NaNs
writer = pd.ExcelWriter('NaN_table.xlsx')
for res_key, df in nan_tables.items():
df.to_excel(writer, res_key)
writer.save()
Save/Load the patched data sets
data_sets['15min'].to_pickle('patched_15.pickle')
data_sets['30min'].to_pickle('patched_30.pickle')
data_sets['60min'].to_pickle('patched_60.pickle')
entso_e['15min'].to_pickle('patched_entso_e_15.pickle')
entso_e['30min'].to_pickle('patched_entso_e_30.pickle')
entso_e['60min'].to_pickle('patched_entso_e_60.pickle')
#data_sets = {}
data_sets['15min'] = pd.read_pickle('patched_15.pickle')
data_sets['30min'] = pd.read_pickle('patched_30.pickle')
data_sets['60min'] = pd.read_pickle('patched_60.pickle')
entso_e['15min'] = pd.read_pickle('patched_entso_e_15.pickle')
entso_e['30min'] = pd.read_pickle('patched_entso_e_30.pickle')
entso_e['60min'] = pd.read_pickle('patched_entso_e_60.pickle')
For 50 Hertz, it is already in the data. For TenneT, it is calculated by substracting offshore from total generation. For Amprion and TransnetBW, onshore wind generation is just total wind generation. Takes <1 second to run.
# Some of the following operations require the Dataframes to be lexsorted in
# the columns
for res_key, df in data_sets.items():
df.sort_index(axis=1, inplace=True)
for area, source in zip(['DE_amprion', 'DE_tennet', 'DE_transnetbw'],
['Amprion', 'TenneT', 'TransnetBW']):
new_col_header = {
'variable': 'wind_onshore',
'region': '{tso}',
'attribute': 'generation',
'source': 'own calculation',
'web': '',
'unit': 'MW'
}
if area == 'DE_tennet':
colname = ('DE_tennet', 'wind_offshore', 'generation', 'TenneT')
offshore = data_sets['15min'].loc[:, colname]
else:
offshore = 0
data_sets['15min'][
tuple(new_col_header[level].format(tso=area) for level in headers)
] = (data_sets['15min'][(area, 'wind', 'generation', source)] - offshore)
# Sort again
data_sets['15min'].sort_index(axis=1, inplace=True)
Apart from being interesting on it's own, this is also required to calculate an aggregated wind-profile for Germany
new_col_header = {
'variable': 'wind',
'region': 'DE',
'attribute': 'capacity',
'source': 'BNetzA and Netztransparenz.de',
'web': 'http://data.open-power-system-data.org/renewable_power_plants',
'unit': 'MW'
}
new_col_header = tuple(new_col_header[level] for level in headers)
data_sets['15min'][new_col_header] = (
data_sets['15min']
.loc[:, ('DE', ['wind_onshore', 'wind_offshore'], 'capacity')]
.sum(axis=1, skipna=False))
# Sort again
data_sets['15min'].sort_index(axis=1, inplace=True)
The wind and solar in-feed data for the 4 German balancing areas is summed up and stored in in new columns, which are then used to calculate profiles, that is, the share of wind/solar capacity producing at a given time. The column headers are created in the fashion introduced in the read script. Takes 5 seconds to run.
for tech in ['solar', 'wind', 'wind_onshore', 'wind_offshore']:
for attribute in ['generation']: # we could also include 'forecast'
sum_col = data_sets['15min'].loc(axis=1)[(
['DE_50hertz', 'DE_amprion', 'DE_tennet', 'DE_transnetbw'],
tech, attribute)].sum(axis=1, skipna=False).to_frame()
# Create a new MultiIndex and append aggregated data to the dataset
new_col_header = {
'variable': '{tech}',
'region': 'DE',
'attribute': '{attribute}',
'source': 'own calculation',
'web': '',
'unit': 'MW'
}
tuples = [tuple(new_col_header[level].format(
tech=tech, attribute=attribute) for level in headers)]
sum_col.columns = pd.MultiIndex.from_tuples(tuples, names=headers)
data_sets['15min'] = data_sets['15min'].combine_first(sum_col)
if not attribute == 'generation':
continue
# Calculate the profile column
profile_col = (sum_col.values * 100 /
data_sets['15min']['DE', tech, 'capacity'])
# Create a new MultiIndex and append aggregated data to the dataset
new_col_header = {
'variable': '{tech}',
'region': 'DE',
'attribute': 'profile',
'source': 'own calculation',
'web': '',
'unit': 'percent'
}
tuples = [tuple(new_col_header[level].format(tech=tech)
for level in headers)]
profile_col.columns = pd.MultiIndex.from_tuples(tuples, names=headers)
data_sets['15min'] = data_sets['15min'].combine_first(profile_col)
Some data comes in 15-minute intervals (i.e. German renewable generation), other in 60-minutes (i.e. load data from ENTSO-E and Prices). We resample the 15-minute data to hourly resolution and append it to the 60-minutes dataset.
The marker column is resampled separately in such a way that all information on where data has been interpolated is preserved.
The .resample('H').mean()
methods calculates the means from the values for 4 quarter hours [:00, :15, :30, :45] of an hour values, inserts that for :00 and drops the other 3 entries. Takes 15 seconds to run.
# Condense marker column from 15 to 60 minutes resolutution
marker_15 = data_sets['15min']['interpolated_values'].groupby(
pd.Grouper(freq='60Min', closed='left', label='left')
).agg(resample_markers)
marker_15 = marker_15.reindex(data_sets['60min'].index)
# Glue condensed 15 min marker onto 60 min marker
marker_60 = data_sets['60min']['interpolated_values']
both_markers = marker_15.notnull() & marker_60.notnull()
only_15 = marker_15.notnull() & marker_60.isnull()
data_sets['60min'].loc[both_markers, 'interpolated_values'] = (
marker_60.str.cat(others=marker_15, sep=' | '))
data_sets['60min'].loc[only_15, 'interpolated_values'] = marker_15
resampled = data_sets['15min'].resample('H').mean()
data_sets['60min'] = data_sets['60min'].combine_first(resampled)
for res_key, df in entso_e.items():
resampled = (df.drop('DE_AT_LU', axis=1, errors='ignore')
.resample('H').mean())
entso_e['60min'] = entso_e['60min'].combine_first(resampled)
# combine with TSO data
if data_sets[res_key].empty:
data_sets[res_key] = df
else:
data_cols = data_sets[res_key].columns.droplevel(['source', 'web', 'unit'])
add_cols = [col for col in df.columns if not col[:3] in data_cols]
add_cols = pd.MultiIndex.from_tuples(add_cols, names=headers)
data_sets[res_key] = data_sets[res_key].combine_first(df[add_cols])
The index column of th data sets defines the start of the timeperiod represented by each row of that data set in UTC time. We include an additional column for the CE(S)T Central European (Summer-) Time, as this might help aligning the output data with other data sources.
info_cols = {'utc': 'utc_timestamp',
'cet': 'cet_cest_timestamp',
'marker': 'interpolated_values'}
for res_key, df in data_sets.items():
if df.empty:
continue
df.index.rename(info_cols['utc'], inplace=True)
df.insert(0, info_cols['cet'],
df.index.tz_localize('UTC').tz_convert('Europe/Brussels'))
Create a final savepoint
data_sets['15min'].to_pickle('final_15.pickle')
data_sets['30min'].to_pickle('final_30.pickle')
data_sets['60min'].to_pickle('final_60.pickle')
data_sets = {}
data_sets['15min'] = pd.read_pickle('final_15.pickle')
data_sets['30min'] = pd.read_pickle('final_30.pickle')
data_sets['60min'] = pd.read_pickle('final_60.pickle')
This section: create the metadata, both general and column-specific. All metadata we be stored as a JSON file. Takes <1s to run.
# change to out_path directory
os.chdir(out_path)
os.getcwd()
make_json(data_sets, info_cols, version, changes, headers, areas)
This section: Save as Data Package (data in CSV, metadata in JSON file). All files are saved in the directory of this notebook. Alternative file formats (SQL, XLSX) are also exported. Takes about 1 hour to run.
Cut off the data outside of [start_from_user:end_from_user]
for res_key, df in data_sets.items():
# First, convert userinput to UTC time to conform with data_set.index
if start_from_user:
start_from_user = (
pytz.timezone('Europe/Brussels')
.localize(datetime.combine(start_from_user, time()))
.astimezone(pytz.timezone('UTC')))
if end_from_user:
end_from_user = (
pytz.timezone('Europe/Brussels')
.localize(datetime.combine(end_from_user, time()))
.astimezone(pytz.timezone('UTC'))
# appropriate offset to inlude the end of period
+ timedelta(days=1, minutes=-int(res_key[:2])))
# Then cut off the data_set
data_sets[res_key] = df.loc[start_from_user:end_from_user, :]
Data are provided in three different "shapes":
The different shapes need to be created internally befor they can be saved to files. Takes about 1 minute to run.
data_sets_singleindex = {}
data_sets_multiindex = {}
data_sets_stacked = {}
for res_key, df in data_sets.items():
if df.empty:
continue
for col_name, col in df.iteritems():
if not (col_name[0] in info_cols.values() or
col_name[2] == 'profile'):
df[col_name] = col.round(0)
# MultIndex
data_sets_multiindex[res_key + '_multiindex'] = df
# SingleIndex
df_singleindex = df.copy()
# use first 3 levels of multiindex to create singleindex
df_singleindex.columns = [
col[0] if col[0] in info_cols.values()
else '_'.join([level for level in col[0:3] if not level == ''])
for col in df.columns.values]
data_sets_singleindex[res_key + '_singleindex'] = df_singleindex
# Stacked
stacked = df.copy()
stacked.drop(info_cols['cet'], axis=1, inplace=True)
stacked.columns = stacked.columns.droplevel(['source', 'web', 'unit'])
stacked = stacked.transpose().stack(dropna=True).to_frame(name='data')
data_sets_stacked[res_key + '_stacked'] = stacked
This file format is required for the filtering function on the OPSD website. This takes about 30 seconds to complete.
for res_key, df in data_sets_singleindex.items():
table = 'time_series_' + res_key
df = df.copy()
df.index = df.index.strftime('%Y-%m-%dT%H:%M:%SZ')
df[info_cols['cet']] = (
df[info_cols['cet']].dt.strftime('%Y-%m-%dT%H:%M:%S%z'))
df.to_sql(table, sqlite3.connect('time_series.sqlite'),
if_exists='replace', index_label=info_cols['utc'])
Writing the full tables to Excel takes extremely long. As a workaround, only the first 5 rows are exported. The rest of the data can than be inserted manually from the _multindex.csv
files.
writer = pd.ExcelWriter('time_series1.xlsx')
for res_key, df in data_sets_multiindex.items():
df.head().to_excel(writer, res_key.split('_')[0], float_format='%.2f',
merge_cells=True)
# merge_cells=False doesn't work properly with multiindex
writer.save()
This takes about 10 minutes to complete.
# itertoools.chain() allows iterating over multiple dicts at once
for res_stacking_key, df in itertools.chain(
# data_sets_singleindex.items(),
# data_sets_multiindex.items(),
data_sets_stacked.items()
):
# convert the format of the cet_cest-timestamp to ISO-8601
if not (res_stacking_key.split('_')[1] == 'stacked'
or type(df.iloc[0,0]) == str):
df.iloc[:,0] = df.iloc[:,0].dt.strftime('%Y-%m-%dT%H:%M:%S%z')
filename = 'time_series_' + res_stacking_key + '.csv'
df.to_csv(filename, float_format='%.2f',
date_format='%Y-%m-%dT%H:%M:%SZ')
We publish SHA-checksums for the outputfiles on GitHub to allow verifying the integrity of outputfiles on the OPSD server.
def get_sha_hash(path, blocksize=65536):
sha_hasher = hashlib.sha256()
with open(path, 'rb') as f:
buffer = f.read(blocksize)
while len(buffer) > 0:
sha_hasher.update(buffer)
buffer = f.read(blocksize)
return sha_hasher.hexdigest()
files = os.listdir(out_path)
# Create checksums.txt in the output directory
with open('checksums.txt', 'w') as f:
for file_name in files:
if file_name.split('.')[-1] in ['csv', 'sqlite', 'xlsx']:
file_hash = get_sha_hash(file_name)
f.write('{},{}\n'.format(file_name, file_hash))
# Copy the file to root directory from where it will be pushed to GitHub,
# leaving a copy in the version directory for reference
copyfile('checksums.txt', os.path.join(home_path, 'checksums.txt'))