# Path: jr/meg/base.py
# def make_meta_epochs(epochs, y, n_bin=100):
#     from scipy.stats import trim_mean
#     from mne.epochs import EpochsArray
#     meta_data = list()  # EEG data
#     meta_y = list()  # regressors
#     n = len(epochs)
# 
#     # make continuous y into bins to become categorical
#     if len(np.unique(y)) < n_bin:
#         hist, bin_edge = np.histogram(y, n_bin)
#         y_ = y
#         for low, high in zip(bin_edge[:-1], bin_edge[1:]):
#             sel = np.where((y >= low) & (y < high))[0]
#             y_[sel] = .5 * (high + low)
#         y = y_
# 
#     # if discrete and few categories
#     if len(np.unique(y)) < n_bin:
#         already_used = list()
#         for this_y in np.unique(y):
#             for ii in range(n / len(np.unique(y)) / n_bin):
#                 sel = np.where(y == this_y)[0]
#                 sel = [ii for ii in sel if ii not in already_used][:n_bin]
#                 if not len(sel):
#                     continue
#                 meta_data.append(trim_mean(epochs._data[sel, :, :], .05,
#                                            axis=0))
#                 meta_y.append(this_y)
#                 already_used += sel
#     else:
#         hist, bin_edge = np.histogram(y, n_bin)
#         for low, high in zip(bin_edge[:-1], bin_edge[1:]):
#             sel = np.where((y >= low) & (y < high))[0]
#             this_y = .5 * (high + low)
#             if not len(sel):
#                 continue
#             meta_data.append(trim_mean(epochs._data[sel, :, :], .05, axis=0))
#             meta_y.append(this_y)
# 
#     events = np.vstack((np.zeros(len(meta_y)),
#                         np.zeros(len(meta_y)), meta_y)).T
#     events = np.array(np.round(events), int)
# 
#     # transform into epochs
#     new_epochs = EpochsArray(meta_data, epochs.info, events=events,
#                              verbose=False)
#     new_epochs.events = np.array(new_epochs.events, float)
#     new_epochs.events[:, 2] = meta_y
# 
#     # XXX why change time and sfreq?
#     new_epochs.times = epochs.times
#     new_epochs.info['sfreq'] = epochs.info['sfreq']
#     return new_epochs


from copy import deepcopy
from ..meg import make_meta_epochs
        from mne.decoding import GeneralizationAcrossTime
    from gat.utils import GAT
    from mne.decoding import GeneralizationAcrossTime
        from sklearn.cross_validation import check_cv, StratifiedKFold
        from mne.decoding.time_gen import _check_epochs_input
        from mne.decoding import TimeDecoding
        from mne import EpochsArray, create_info
        from mne.decoding import TimeDecoding
        from mne import EpochsArray
        from mne.time_frequency import single_trial_power
    from nose.tools import assert_true
    from jr.gat import get_diagonal_ypred
import numpy as np
        cmb_gat.cv_.test_folds[sel] = gat.cv_.test_folds
        cmb_gat.cv_.y[sel] = gat.cv_.y
        for t_train in range(len(gat.y_pred_)):
            for t_test in range(len(gat.y_pred_[t_train])):
                cmb_gat.y_pred_[t_train][t_test][sel, :] = \
                    gat.y_pred_[t_train][t_test]
    # clean
    for att in ['scores_', 'scorer_', 'y_true_']:
        if hasattr(cmb_gat, att):
            delattr(cmb_gat, att)
    return cmb_gat


class MetaGAT(object):
    def __init__(self, gat, n=100):
        self.cv = gat.cv
        self.gat = gat
        self.n = n

    def fit(self, epochs, y=None):
        X, y, self.gat.picks_ = _check_epochs_input(epochs, y, self.gat.picks)
        gat_list = list()

        cv = self.cv
        if isinstance(cv, (int, np.int)):
            cv = StratifiedKFold(y, cv)
        cv = check_cv(cv, X, y, classifier=True)
        # Construct meta epoch and fit gat with a single fold
        for ii, (train, test) in enumerate(cv):
            # meta trial

# Path: jr/meg/base.py
# def make_meta_epochs(epochs, y, n_bin=100):
#     from scipy.stats import trim_mean
#     from mne.epochs import EpochsArray
#     meta_data = list()  # EEG data
#     meta_y = list()  # regressors
#     n = len(epochs)
# 
#     # make continuous y into bins to become categorical
#     if len(np.unique(y)) < n_bin:
#         hist, bin_edge = np.histogram(y, n_bin)
#         y_ = y
#         for low, high in zip(bin_edge[:-1], bin_edge[1:]):
#             sel = np.where((y >= low) & (y < high))[0]
#             y_[sel] = .5 * (high + low)
#         y = y_
# 
#     # if discrete and few categories
#     if len(np.unique(y)) < n_bin:
#         already_used = list()
#         for this_y in np.unique(y):
#             for ii in range(n / len(np.unique(y)) / n_bin):
#                 sel = np.where(y == this_y)[0]
#                 sel = [ii for ii in sel if ii not in already_used][:n_bin]
#                 if not len(sel):
#                     continue
#                 meta_data.append(trim_mean(epochs._data[sel, :, :], .05,
#                                            axis=0))
#                 meta_y.append(this_y)
#                 already_used += sel
#     else:
#         hist, bin_edge = np.histogram(y, n_bin)
#         for low, high in zip(bin_edge[:-1], bin_edge[1:]):
#             sel = np.where((y >= low) & (y < high))[0]
#             this_y = .5 * (high + low)
#             if not len(sel):
#                 continue
#             meta_data.append(trim_mean(epochs._data[sel, :, :], .05, axis=0))
#             meta_y.append(this_y)
# 
#     events = np.vstack((np.zeros(len(meta_y)),
#                         np.zeros(len(meta_y)), meta_y)).T
#     events = np.array(np.round(events), int)
# 
#     # transform into epochs
#     new_epochs = EpochsArray(meta_data, epochs.info, events=events,
#                              verbose=False)
#     new_epochs.events = np.array(new_epochs.events, float)
#     new_epochs.events[:, 2] = meta_y
# 
#     # XXX why change time and sfreq?
#     new_epochs.times = epochs.times
#     new_epochs.info['sfreq'] = epochs.info['sfreq']
#     return new_epochs


# Path: jr/gat/base.py
from copy import deepcopy
from ..meg import make_meta_epochs
        from mne.decoding import GeneralizationAcrossTime
    from gat.utils import GAT
    from mne.decoding import GeneralizationAcrossTime
        from sklearn.cross_validation import check_cv, StratifiedKFold
        from mne.decoding.time_gen import _check_epochs_input
        from mne.decoding import TimeDecoding
        from mne import EpochsArray, create_info
        from mne.decoding import TimeDecoding
        from mne import EpochsArray
        from mne.time_frequency import single_trial_power
    from nose.tools import assert_true
    from jr.gat import get_diagonal_ypred
import numpy as np

        cmb_gat.cv_.test_folds[sel] = gat.cv_.test_folds
        cmb_gat.cv_.y[sel] = gat.cv_.y
        for t_train in range(len(gat.y_pred_)):
            for t_test in range(len(gat.y_pred_[t_train])):
                cmb_gat.y_pred_[t_train][t_test][sel, :] = \
                    gat.y_pred_[t_train][t_test]
    # clean
    for att in ['scores_', 'scorer_', 'y_true_']:
        if hasattr(cmb_gat, att):
            delattr(cmb_gat, att)
    return cmb_gat


class MetaGAT(object):
    def __init__(self, gat, n=100):
        self.cv = gat.cv
        self.gat = gat
        self.n = n

    def fit(self, epochs, y=None):
        X, y, self.gat.picks_ = _check_epochs_input(epochs, y, self.gat.picks)
        gat_list = list()

        cv = self.cv
        if isinstance(cv, (int, np.int)):
            cv = StratifiedKFold(y, cv)
        cv = check_cv(cv, X, y, classifier=True)
        # Construct meta epoch and fit gat with a single fold
        for ii, (train, test) in enumerate(cv):
            # meta trial

            epochs_ = make_meta_epochs(epochs[train], y[train], n_bin=self.n)