<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 tsam - 1. Example
Example usage of the time series aggregation module (tsam)
Date
Step1:  Input data
Read in time series from testdata.csv with pandas
Step2:  Show a slice of the dataset
Step3:  Show the shape of the raw input data
Step4:  Create a plot function for the temperature for a visual comparison of the time series
Step5:  Plot an example series - in this case the temperature
Step6:  Simple k-mean aggregation
Initialize an aggregation class object with k-mean as method for eight typical days, without any integration of extreme periods. Alternative clusterMethod's are 'averaging','hierarchical', 'k_medoids' and 'k_maxoids'.
Step7:  Create the typical periods
Step8:  Show shape of typical periods
Step9:  Save typical periods to .csv file
Step10:  Repredict the original time series based on the typical periods
Step11:  Plot the repredicted data
Step12:  As seen, they days with the minimal temperature are excluded. In case that they are required they can be added to the aggregation as follow.
k-maxoids aggregation including extreme periods
Initialize a time series aggregation based on k-maxoids, which automatically searches for points closest to the convex hull.
Step13:  Create the typical periods
Step14:  The aggregation can also be evaluated by indicators
Step15:  Repredict the original time series based on the typical periods
Step16:  Plot repredicted data
Step17:  Here bigger biggest values and lower lowest values can be observed compared to k-means clustering.
Comparison of the aggregations
It was shown for the temperature, but both times all four time series have been aggregated. Therefore, we compare here also the duration curves  of the electrical load for the original time series, the aggregation with k-mean, and the k-maxoids aggregation.
Step18:  Or as unsorted time series for an example week
<ASSISTANT_TASK:>
Python Code:
%load_ext autoreload
%autoreload 2
import copy
import os
import pandas as pd
import matplotlib.pyplot as plt
import tsam.timeseriesaggregation as tsam
%matplotlib inline
Explanation: tsam - 1. Example
Example usage of the time series aggregation module (tsam)
Date: 02.05.2020
Author: Maximilian Hoffmann
Import pandas and the relevant time series aggregation class
End of explanation
raw = pd.read_csv('testdata.csv', index_col = 0)
Explanation: Input data
Read in time series from testdata.csv with pandas
End of explanation
raw.head()
Explanation: Show a slice of the dataset
End of explanation
raw.shape
Explanation: Show the shape of the raw input data: 4 types of timeseries (GHI, Temperature, Wind and Load) for every hour in a year
End of explanation
def plotTS(data, periodlength, vmin, vmax):
    fig, axes = plt.subplots(figsize = [6, 2], dpi = 100, nrows = 1, ncols = 1)
    stacked, timeindex = tsam.unstackToPeriods(copy.deepcopy(data), periodlength)
    cax = axes.imshow(stacked.values.T, interpolation = 'nearest', vmin = vmin, vmax = vmax)
    axes.set_aspect('auto')  
    axes.set_ylabel('Hour')
    plt.xlabel('Day')
    fig.subplots_adjust(right = 1.2)
    cbar=plt.colorbar(cax)    
    cbar.set_label('T [°C]')
Explanation: Create a plot function for the temperature for a visual comparison of the time series
End of explanation
plotTS(raw['T'], 24, vmin = raw['T'].min(), vmax = raw['T'].max())
Explanation: Plot an example series - in this case the temperature
End of explanation
aggregation = tsam.TimeSeriesAggregation(raw, noTypicalPeriods = 8, hoursPerPeriod = 24, 
                                        clusterMethod = 'k_means')
Explanation: Simple k-mean aggregation
Initialize an aggregation class object with k-mean as method for eight typical days, without any integration of extreme periods. Alternative clusterMethod's are 'averaging','hierarchical', 'k_medoids' and 'k_maxoids'.
End of explanation
typPeriods = aggregation.createTypicalPeriods()
Explanation: Create the typical periods
End of explanation
typPeriods.shape
Explanation: Show shape of typical periods: 4 types of timeseries for 8*24 hours
End of explanation
typPeriods.to_csv(os.path.join('results','testperiods_kmeans.csv'))
Explanation: Save typical periods to .csv file
End of explanation
predictedPeriods = aggregation.predictOriginalData()
Explanation: Repredict the original time series based on the typical periods
End of explanation
plotTS(predictedPeriods['T'], 24, vmin = raw['T'].min(), vmax = raw['T'].max())
Explanation: Plot the repredicted data
End of explanation
aggregationMax = tsam.TimeSeriesAggregation(raw, noTypicalPeriods = 8, hoursPerPeriod = 24, 
                                            clusterMethod = 'k_maxoids', rescaleClusterPeriods=False)
Explanation: As seen, they days with the minimal temperature are excluded. In case that they are required they can be added to the aggregation as follow.
k-maxoids aggregation including extreme periods
Initialize a time series aggregation based on k-maxoids, which automatically searches for points closest to the convex hull.
End of explanation
typPeriodsMax = aggregationMax.createTypicalPeriods()
Explanation: Create the typical periods
End of explanation
aggregationMax.accuracyIndicators()
Explanation: The aggregation can also be evaluated by indicators
End of explanation
predictedPeriodsMax = aggregationMax.predictOriginalData()
Explanation: Repredict the original time series based on the typical periods
End of explanation
plotTS(predictedPeriodsMax['T'], 24, vmin = raw['T'].min(), vmax = raw['T'].max())
Explanation: Plot repredicted data
End of explanation
fig, axes = plt.subplots(figsize = [6, 2], dpi = 100, nrows = 1, ncols = 1)
raw['Load'].sort_values(ascending=False).reset_index(drop=True).plot(label = 'Original')
predictedPeriods['Load'].sort_values(ascending=False).reset_index(drop=True).plot(label = '8 typ days \n + (Centroids)')
predictedPeriodsMax['Load'].sort_values(
    ascending=False).reset_index(drop=True).plot(label = '8 typ days \n + (Maxoids)')
plt.legend()
plt.xlabel('Hours [h]')
plt.ylabel('Duration Load [MW]')
Explanation: Here bigger biggest values and lower lowest values can be observed compared to k-means clustering.
Comparison of the aggregations
It was shown for the temperature, but both times all four time series have been aggregated. Therefore, we compare here also the duration curves  of the electrical load for the original time series, the aggregation with k-mean, and the k-maxoids aggregation.
End of explanation
fig, axes = plt.subplots(figsize = [6, 2], dpi = 100, nrows = 1, ncols = 1)
raw['Load']['20100210':'20100218'].plot(label = 'Original')
predictedPeriods['Load']['20100210':'20100218'].plot(label = '8 typ days \n + (Centroids)')
predictedPeriodsMax['Load']['20100210':'20100218'].plot(label = '8 typ days \n + (Maxoids)')
plt.legend()
plt.ylabel('Load [MW]')
Explanation: Or as unsorted time series for an example week
End of explanation
<END_TASK>