from cesium import featurize
import pandas as pd

# mock up ts data

df = pd.DataFrame({
   "group": ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'b'],
   "time": [1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5],
   "x": [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23],
   "y": [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24],
})

df

from cesium import datasets
import numpy as np

eeg = datasets.fetch_andrzejak()

# Group together classes (Z, O), (N, F), (S) as normal, interictal, ictal
eeg["classes"] = eeg["classes"].astype("U16") #  allocate memory for longer class names
eeg["classes"][np.logical_or(eeg["classes"]=="Z", eeg["classes"]=="O")] = "Normal"
eeg["classes"][np.logical_or(eeg["classes"]=="N", eeg["classes"]=="F")] = "Interictal"
eeg["classes"][eeg["classes"]=="S"] = "Ictal"

pd.DataFrame(eeg).head()

"""
Explanation: Try Cesium

Feature list: http://cesium-ml.org/docs/feature_table.html
Example: https://github.com/cesium-ml/cesium/blob/master/examples/plot_EEG_Example.py
It has built-in model prediction for its special input data structure

Summary

It's easy to add customized ts features with Cesium
To use expanding or rolling window, its input has a special data structure, which puts a window of data in a list at each row
Comparing with tsfresh, it's doesn't have much flexibility to modify feature extraction settings or params
End of explanation
"""


features_to_use = ["amplitude",
                   "percent_beyond_1_std",
                   "flux_percentile_ratio_mid20",
                   "maximum",
                   "max_slope",
                   "median",
                   "median_absolute_deviation",
                   "percent_close_to_median",
                   "minimum",
                   "skew",
                   "std",
                   "weighted_average"]

fset_cesium = featurize.featurize_time_series(times=eeg["times"],
                                              values=eeg["measurements"],
                                              errors=None,
                                              features_to_use=features_to_use)

fset_cesium

print(np.median(eeg['measurements'][0]), np.median(eeg['measurements'][1]), np.median(eeg['measurements'][2]))

"""
Explanation: Generate selected features
End of explanation
"""


import scipy.stats

def hanhan_mean_signal2(t, m, e):
    return np.mean(m)*2

def hanhan_std_signal2(t, m, e):
    return np.std(m)*2

guo_features = {
    "mean2": hanhan_mean_signal2,
    "std2": hanhan_std_signal2
}

fset_guo = featurize.featurize_time_series(times=eeg["times"], values=eeg["measurements"],
                                           errors=None,
                                           features_to_use=list(guo_features.keys()),
                                           custom_functions=guo_features)
fset_guo.head()

"""
Explanation: Generate customized features
End of explanation
"""


