# Path: maxdiv/preproc.py
# def get_available_methods():
# def local_linear_regression(X, window_size=5):
# def td(X, k = None, T = 1, opt_th = 0.05):
# def td_params(X, k = None, T = 1, opt_th = 0.05):
# def normalize_time_series(ts):
# def detect_periods(ts):
# def deseasonalize_ft(ts):
# def deseasonalize_zscore(ts, period_len):
# def detrend_linear(ts):
# def detrend_ols(ts, periods = None, linear_trend = True, linear_season_trend = False, return_model_params = False):
# def pca_projection(X, k):
# def sparse_random_projection(X, k):
#         C = np.zeros(dimension*dimension)
#         P = np.linspace(0.0, 1.0, end-start)
#         P = np.vstack( [P, np.ones(P.shape)] )
#             T = int(context_size // max_k) + 1
#             T = max(1, int(round(context_size / k)))
#     N = len(ts) if ts.ndim == 1 else ts.shape[1]
#     A = np.hstack((np.arange(0.0, float(N)).reshape((N, 1)), np.ones((N, 1))))
#     A = np.zeros((func.shape[1], num_params))
#     A[:,0] = 1
#         A[:,1] = np.arange(0.0, func.shape[1])
#     C = (X.T - X.mean(axis = 1)).T
#     R = np.ma.cov(C).filled(0)
# 
# Path: maxdiv/eval.py
# def auc(ygt, regions, n = 0):
# def average_precision(ygt, regions, overlap = 0.5, plot = False):
# def recall_precision(ygt, regions, overlap = 0.5, th = None, multiAsFP = True):
# def plotDetections(func, regions, gt = [], ticks = None, export = None, silent = True, detailedvis = False):
# def show_interval(f, a, b, visborder=100, color='b', alpha=0.3, plot_function=True, border=False):
# def pointwiseLabelsToIntervals(labels):
# 
# Path: maxdiv/libmaxdiv_wrapper.py
# class detection_t(Structure):
# class pointwise_proposal_params_t(Structure):
# class erph_params_t(Structure):
# class embedding_params_t(Structure):
# class detrending_params_t(Structure):
# class projection_params_t(Structure):
# class preproc_params_t(Structure):
# class maxdiv_params_t(Structure):
# class _LibMaxDiv(object):
#     def __init__(self, library):
#     def _register_func(self, funcName, paramtypes, paramflags, errcheck = None):
#     def _errcheck_compile_pipeline(result, func, args):
# def _search_libmaxdiv():
# def maxdiv(X, method = 'gaussian_cov', num_intervals = 1, proposals = 'dense', **kwargs):
# def maxdiv_exec(X, params, num_intervals = 1):
# def maxdiv_score_intervals(X, params, intervals):
#         X = X.reshape((1, len(X)))
#                     X = preproc.local_linear_regression(X)
#                     X = preproc.deseasonalize_ft(X)
#         X = X.reshape((1, len(X)))
#         X = X.filled(np.nan)
#     X = np.require(X if isSpatioTemporal else X.T, np.float32 if maxdiv_scalar == c_float else np.float64, ['C_CONTIGUOUS'])
#         X = X.reshape((1, len(X)))
#         X = X.filled(np.nan)
#     X = np.require(X if isSpatioTemporal else X.T, np.float32 if maxdiv_scalar == c_float else np.float64, ['C_CONTIGUOUS'])


import sys
import numpy as np
import datasets
from collections import OrderedDict
from maxdiv import preproc, eval, libmaxdiv_wrapper

if PROPOSALS == 'help':
    print('Test several deseasonalization methods in combination with different variants of the MDI algorithm on a given dataset.\n')
    print('Usage: {} <dataset = yahoo | synthetic> <proposals = dense> <td-dim = 6> <td-lag = 2>'.format(sys.argv[0]))
    exit()

# Load test data
if DATASET == 'synthetic':
    data = datasets.loadDatasets('synthetic_seasonal')['diurnal']
else:
    data = datasets.loadDatasets('yahoo_real')['A1Benchmark']

# Check libmaxdiv
if libmaxdiv_wrapper.libmaxdiv is None:
    raise RuntimeError('libmaxdiv could not be found and loaded.')

# Compile pipelines
pipelines = OrderedDict()
pipelines['none'] = []
pipelines['OLS'] = []
pipelines['Z-Score'] = []
params = libmaxdiv_wrapper.maxdiv_params_t()
libmaxdiv_wrapper.libmaxdiv.maxdiv_init_params(params)
params.min_size[0] = 20 if DATASET == 'synthetic' else 10
params.max_size[0] = 100 if DATASET == 'synthetic' else 120
params.proposal_generator = libmaxdiv_wrapper.enums['MAXDIV_DENSE_PROPOSALS'] if PROPOSALS == 'dense' else libmaxdiv_wrapper.enums['MAXDIV_POINTWISE_PROPOSALS_' + PROPOSALS.upper()]
params.preproc.normalization = libmaxdiv_wrapper.enums['MAXDIV_NORMALIZE_MAX']
params.preproc.embedding.kt = TD_DIM
params.preproc.embedding.dt = TD_LAG
params.preproc.detrending.ols_period_num = PERIOD_LEN

# Path: maxdiv/preproc.py
# def get_available_methods():
# def local_linear_regression(X, window_size=5):
# def td(X, k = None, T = 1, opt_th = 0.05):
# def td_params(X, k = None, T = 1, opt_th = 0.05):
# def normalize_time_series(ts):
# def detect_periods(ts):
# def deseasonalize_ft(ts):
# def deseasonalize_zscore(ts, period_len):
# def detrend_linear(ts):
# def detrend_ols(ts, periods = None, linear_trend = True, linear_season_trend = False, return_model_params = False):
# def pca_projection(X, k):
# def sparse_random_projection(X, k):
#         C = np.zeros(dimension*dimension)
#         P = np.linspace(0.0, 1.0, end-start)
#         P = np.vstack( [P, np.ones(P.shape)] )
#             T = int(context_size // max_k) + 1
#             T = max(1, int(round(context_size / k)))
#     N = len(ts) if ts.ndim == 1 else ts.shape[1]
#     A = np.hstack((np.arange(0.0, float(N)).reshape((N, 1)), np.ones((N, 1))))
#     A = np.zeros((func.shape[1], num_params))
#     A[:,0] = 1
#         A[:,1] = np.arange(0.0, func.shape[1])
#     C = (X.T - X.mean(axis = 1)).T
#     R = np.ma.cov(C).filled(0)
# 
# Path: maxdiv/eval.py
# def auc(ygt, regions, n = 0):
# def average_precision(ygt, regions, overlap = 0.5, plot = False):
# def recall_precision(ygt, regions, overlap = 0.5, th = None, multiAsFP = True):
# def plotDetections(func, regions, gt = [], ticks = None, export = None, silent = True, detailedvis = False):
# def show_interval(f, a, b, visborder=100, color='b', alpha=0.3, plot_function=True, border=False):
# def pointwiseLabelsToIntervals(labels):
# 
# Path: maxdiv/libmaxdiv_wrapper.py
# class detection_t(Structure):
# class pointwise_proposal_params_t(Structure):
# class erph_params_t(Structure):
# class embedding_params_t(Structure):
# class detrending_params_t(Structure):
# class projection_params_t(Structure):
# class preproc_params_t(Structure):
# class maxdiv_params_t(Structure):
# class _LibMaxDiv(object):
#     def __init__(self, library):
#     def _register_func(self, funcName, paramtypes, paramflags, errcheck = None):
#     def _errcheck_compile_pipeline(result, func, args):
# def _search_libmaxdiv():
# def maxdiv(X, method = 'gaussian_cov', num_intervals = 1, proposals = 'dense', **kwargs):
# def maxdiv_exec(X, params, num_intervals = 1):
# def maxdiv_score_intervals(X, params, intervals):
#         X = X.reshape((1, len(X)))
#                     X = preproc.local_linear_regression(X)
#                     X = preproc.deseasonalize_ft(X)
#         X = X.reshape((1, len(X)))
#         X = X.filled(np.nan)
#     X = np.require(X if isSpatioTemporal else X.T, np.float32 if maxdiv_scalar == c_float else np.float64, ['C_CONTIGUOUS'])
#         X = X.reshape((1, len(X)))
#         X = X.filled(np.nan)
#     X = np.require(X if isSpatioTemporal else X.T, np.float32 if maxdiv_scalar == c_float else np.float64, ['C_CONTIGUOUS'])


# Path: experiments/synthetic/test_deseasonalization.py
import sys
import numpy as np
import datasets
from collections import OrderedDict
from maxdiv import preproc, eval, libmaxdiv_wrapper


if PROPOSALS == 'help':
    print('Test several deseasonalization methods in combination with different variants of the MDI algorithm on a given dataset.\n')
    print('Usage: {} <dataset = yahoo | synthetic> <proposals = dense> <td-dim = 6> <td-lag = 2>'.format(sys.argv[0]))
    exit()

# Load test data
if DATASET == 'synthetic':
    data = datasets.loadDatasets('synthetic_seasonal')['diurnal']
else:
    data = datasets.loadDatasets('yahoo_real')['A1Benchmark']

# Check libmaxdiv
if libmaxdiv_wrapper.libmaxdiv is None:
    raise RuntimeError('libmaxdiv could not be found and loaded.')

# Compile pipelines
pipelines = OrderedDict()
pipelines['none'] = []
pipelines['OLS'] = []
pipelines['Z-Score'] = []
params = libmaxdiv_wrapper.maxdiv_params_t()
libmaxdiv_wrapper.libmaxdiv.maxdiv_init_params(params)
params.min_size[0] = 20 if DATASET == 'synthetic' else 10
params.max_size[0] = 100 if DATASET == 'synthetic' else 120
params.proposal_generator = libmaxdiv_wrapper.enums['MAXDIV_DENSE_PROPOSALS'] if PROPOSALS == 'dense' else libmaxdiv_wrapper.enums['MAXDIV_POINTWISE_PROPOSALS_' + PROPOSALS.upper()]
params.preproc.normalization = libmaxdiv_wrapper.enums['MAXDIV_NORMALIZE_MAX']
params.preproc.embedding.kt = TD_DIM
params.preproc.embedding.dt = TD_LAG
params.preproc.detrending.ols_period_num = PERIOD_LEN

params.preproc.detrending.z_period_len = PERIOD_LEN