# 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
        params.kl_mode = libmaxdiv_wrapper.enums['MAXDIV_KL_I_OMEGA']
    else:
        params.divergence = libmaxdiv_wrapper.enums['MAXDIV_KL_DIVERGENCE']
        params.kl_mode = libmaxdiv_wrapper.enums['MAXDIV_KL_' + mode]
    
    params.preproc.detrending.method = libmaxdiv_wrapper.enums['MAXDIV_DETREND_NONE']
    pipelines['none'].append(libmaxdiv_wrapper.libmaxdiv.maxdiv_compile_pipeline(params))
    params.preproc.detrending.method = libmaxdiv_wrapper.enums['MAXDIV_DETREND_OLS']
    pipelines['OLS'].append(libmaxdiv_wrapper.libmaxdiv.maxdiv_compile_pipeline(params))
    params.preproc.detrending.method = libmaxdiv_wrapper.enums['MAXDIV_DETREND_ZSCORE']
    pipelines['Z-Score'].append(libmaxdiv_wrapper.libmaxdiv.maxdiv_compile_pipeline(params))

# Run detectors
aps = OrderedDict()
aps['none'] = []
aps['FT'] = []
aps['OLS'] = []
aps['Z-Score'] = []
for detrending in aps.keys():
    pipeline_key = 'none' if detrending == 'FT' else detrending
    for i, (method, mode) in enumerate(METHODS):
        sys.stderr.write('{}, {}, {}\n'.format(detrending, method, mode))
        ygts = []
        regions = []
        
        for func in data:
            ygts.append(func['gt'])
            ts = preproc.deseasonalize_ft(func['ts']) if detrending == 'FT' else func['ts']
            regions.append(libmaxdiv_wrapper.maxdiv_exec(ts, pipelines[pipeline_key][i], None))
        

# 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

        params.kl_mode = libmaxdiv_wrapper.enums['MAXDIV_KL_I_OMEGA']
    else:
        params.divergence = libmaxdiv_wrapper.enums['MAXDIV_KL_DIVERGENCE']
        params.kl_mode = libmaxdiv_wrapper.enums['MAXDIV_KL_' + mode]
    
    params.preproc.detrending.method = libmaxdiv_wrapper.enums['MAXDIV_DETREND_NONE']
    pipelines['none'].append(libmaxdiv_wrapper.libmaxdiv.maxdiv_compile_pipeline(params))
    params.preproc.detrending.method = libmaxdiv_wrapper.enums['MAXDIV_DETREND_OLS']
    pipelines['OLS'].append(libmaxdiv_wrapper.libmaxdiv.maxdiv_compile_pipeline(params))
    params.preproc.detrending.method = libmaxdiv_wrapper.enums['MAXDIV_DETREND_ZSCORE']
    pipelines['Z-Score'].append(libmaxdiv_wrapper.libmaxdiv.maxdiv_compile_pipeline(params))

# Run detectors
aps = OrderedDict()
aps['none'] = []
aps['FT'] = []
aps['OLS'] = []
aps['Z-Score'] = []
for detrending in aps.keys():
    pipeline_key = 'none' if detrending == 'FT' else detrending
    for i, (method, mode) in enumerate(METHODS):
        sys.stderr.write('{}, {}, {}\n'.format(detrending, method, mode))
        ygts = []
        regions = []
        
        for func in data:
            ygts.append(func['gt'])
            ts = preproc.deseasonalize_ft(func['ts']) if detrending == 'FT' else func['ts']
            regions.append(libmaxdiv_wrapper.maxdiv_exec(ts, pipelines[pipeline_key][i], None))
        

        aps[detrending].append(eval.average_precision(ygts, regions))