<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 - Optimal combination of segments and periods for building supply systems
Date
Step1:  Input data
Read in time series from testdata.csv with pandas
Step2:  Create a plot function for a visual comparison of the time series
Step3:  Plot an example series - in this case the temperature
Step4:  Tune a hierarchical aggregation with segments in combination with duration representation
Step5:  And determine the pareto optimal aggregation up to 200 total time steps. This may take some time...
Step6:  And show the results for the last aggregation
<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
import tsam.hyperparametertuning as tune
import tqdm
%matplotlib inline
Explanation: tsam - Optimal combination of segments and periods for building supply systems
Date: 29.05.2022
Author: Leander Kotzur
Import pandas and the relevant time series aggregation class
End of explanation
raw = pd.read_csv('testdata.csv', index_col = 0)
raw=raw.rename(columns={'T': 'Temperature [°C]', 'Load':'Load [kW]', 'Wind':'Wind [m/s]', 'GHI': 'Solar [W/m²]'})
raw.drop(columns=['Wind [m/s]',], inplace=True)
Explanation: Input data
Read in time series from testdata.csv with pandas
End of explanation
def plotTS(plot_data, raw_data, periodlength=24):
    fig, axes = plt.subplots(figsize = [7, 6], dpi = 100, nrows = raw_data.shape[1], ncols = 1)
    for i, column in enumerate(raw.columns):
        data = plot_data[column]
        stacked, timeindex = tsam.unstackToPeriods(copy.deepcopy(data), periodlength)
        cax = axes[i].imshow(stacked.values.T, interpolation = 'nearest', vmin = raw_data[column].min(), vmax = raw_data[column].max(), origin='lower')
        axes[i].set_aspect('auto')  
        axes[i].set_ylabel('Hour')
        plt.xlabel('Day in the year')
        cbar=plt.colorbar(cax, ax=axes[i], pad=0.01, aspect=7)
        cbar.set_label(column)
    fig.subplots_adjust(right = 1.1, hspace = 0.05)
Explanation: Create a plot function for a visual comparison of the time series
End of explanation
plotTS(raw,raw,periodlength=24)
Explanation: Plot an example series - in this case the temperature
End of explanation
tunedAggregations = tune.HyperTunedAggregations(
    tsam.TimeSeriesAggregation(
        raw,
        hoursPerPeriod=24,
        clusterMethod="hierarchical",
        representationMethod="durationRepresentation",
        distributionPeriodWise=False,
        rescaleClusterPeriods=False,
        segmentation=True,
    )
)
Explanation: Tune a hierarchical aggregation with segments in combination with duration representation
End of explanation
tunedAggregations.identifyParetoOptimalAggregation(untilTotalTimeSteps=100)
Explanation: And determine the pareto optimal aggregation up to 200 total time steps. This may take some time...
End of explanation
predictedPeriods = tunedAggregations.aggregationHistory[-1].predictOriginalData()
plotTS(predictedPeriods,raw,periodlength=24)
tunedAggregations._segmentHistory[-1]
tunedAggregations._periodHistory[-1]
aggregation=tsam.TimeSeriesAggregation(
        raw,
        hoursPerPeriod=24,
        noSegments=8,
        noTypicalPeriods=14,
        clusterMethod="hierarchical",
        rescaleClusterPeriods=False,
        segmentation=True,
        representationMethod="distributionAndMinMaxRepresentation",
        distributionPeriodWise=False
    )
plotTS(aggregation.predictOriginalData(), raw,periodlength=24)
Explanation: And show the results for the last aggregation
End of explanation
<END_TASK>