# Path: ephypype/fif2array.py
# def _get_raw_array(raw_fname, save_data=True):
#     """Read a raw data from **.fif** file and save the data time series, the
#     sensors coordinates and labels in .npy and .txt files.
# 
#     Parameters
#     ----------
#     raw_fname : str
#         pathname of the raw data to read
# 
#     Returns
#     -------
#     array_file : str
#         pathname of the numpy file (.npy) containing the data read from
#         raw_fname
#     channel_coords_file : str
#         pathname of .txt file containing the channels coordinates
#     channel_names_file : str
#         pathname of .txt file containing the channels labels
#     sfreq : float
#         sampling frequency
#     """
#     raw = read_raw_fif(raw_fname, preload=True)
#     subj_path, basename, ext = split_f(raw_fname)
#     select_sensors = mne.pick_types(raw.info, meg=True, ref_meg=False,
#                                     exclude='bads')
# 
#     # save electrode locations
#     sens_loc = [raw.info['chs'][i]['loc'][:3] for i in select_sensors]
#     sens_loc = np.array(sens_loc)
# 
#     channel_coords_file = os.path.abspath('correct_channel_coords.txt')
#     np.savetxt(channel_coords_file, sens_loc, fmt=str("%s"))
# 
#     # save electrode names
#     ch_names = np.array([raw.ch_names[pos] for pos in select_sensors],
#                         dtype='str')
# 
#     channel_names_file = os.path.abspath('correct_channel_names.txt')
#     np.savetxt(channel_names_file, ch_names, fmt=str('%s'))
# 
#     if save_data:
#         data, times = raw[select_sensors, :]
#         print((data.shape))
# 
#         array_file = os.path.abspath(basename + '.npy')
#         np.save(array_file, data)
#         print('\n *** TS FILE {} *** \n'.format(array_file))
#     else:
#         array_file = None
#     print('*** raw.info[sfreq] = {}'.format(raw.info['sfreq']))
# 
#     return array_file, channel_coords_file, channel_names_file, raw.info['sfreq']  # noqa


import os
import numpy as np
    import matplotlib.pyplot as plt
from nipype.utils.filemanip import split_filename
from mne import read_epochs
from mne.io import read_raw_fif
from scipy.signal import welch
from .fif2array import _get_raw_array
        from mne.time_frequency import psd_welch
        from mne.time_frequency import psd_multitaper
"""Power functions."""

# Author: Dmitrii Altukhov <dm-altukhov@ya.ru>
#         Annalisa Pascarella <a.pascarella@iac.cnr.it>




def _compute_and_save_psd(data_fname, fmin=0, fmax=120,
                          method='welch', is_epoched=False,
                          n_fft=256, n_overlap=0,
                          picks=None, proj=False, n_jobs=1, verbose=None):
    """Load epochs/raw from file, compute psd and save the result."""

    if is_epoched:
        epochs = read_epochs(data_fname)
    else:
        epochs = read_raw_fif(data_fname, preload=True)

    epochs_meg = epochs.pick_types(meg=True, eeg=False, eog=False, ecg=False)

    if method == 'welch':
        psds, freqs = psd_welch(epochs_meg, fmin=fmin, fmax=fmax)
    elif method == 'multitaper':
        psds, freqs = psd_multitaper(epochs_meg, fmin=fmin, fmax=fmax)
    else:
        raise Exception('nonexistent method for psd computation')


# Path: ephypype/fif2array.py
# def _get_raw_array(raw_fname, save_data=True):
#     """Read a raw data from **.fif** file and save the data time series, the
#     sensors coordinates and labels in .npy and .txt files.
# 
#     Parameters
#     ----------
#     raw_fname : str
#         pathname of the raw data to read
# 
#     Returns
#     -------
#     array_file : str
#         pathname of the numpy file (.npy) containing the data read from
#         raw_fname
#     channel_coords_file : str
#         pathname of .txt file containing the channels coordinates
#     channel_names_file : str
#         pathname of .txt file containing the channels labels
#     sfreq : float
#         sampling frequency
#     """
#     raw = read_raw_fif(raw_fname, preload=True)
#     subj_path, basename, ext = split_f(raw_fname)
#     select_sensors = mne.pick_types(raw.info, meg=True, ref_meg=False,
#                                     exclude='bads')
# 
#     # save electrode locations
#     sens_loc = [raw.info['chs'][i]['loc'][:3] for i in select_sensors]
#     sens_loc = np.array(sens_loc)
# 
#     channel_coords_file = os.path.abspath('correct_channel_coords.txt')
#     np.savetxt(channel_coords_file, sens_loc, fmt=str("%s"))
# 
#     # save electrode names
#     ch_names = np.array([raw.ch_names[pos] for pos in select_sensors],
#                         dtype='str')
# 
#     channel_names_file = os.path.abspath('correct_channel_names.txt')
#     np.savetxt(channel_names_file, ch_names, fmt=str('%s'))
# 
#     if save_data:
#         data, times = raw[select_sensors, :]
#         print((data.shape))
# 
#         array_file = os.path.abspath(basename + '.npy')
#         np.save(array_file, data)
#         print('\n *** TS FILE {} *** \n'.format(array_file))
#     else:
#         array_file = None
#     print('*** raw.info[sfreq] = {}'.format(raw.info['sfreq']))
# 
#     return array_file, channel_coords_file, channel_names_file, raw.info['sfreq']  # noqa


# Path: ephypype/power.py
import os
import numpy as np
    import matplotlib.pyplot as plt
from nipype.utils.filemanip import split_filename
from mne import read_epochs
from mne.io import read_raw_fif
from scipy.signal import welch
from .fif2array import _get_raw_array
        from mne.time_frequency import psd_welch
        from mne.time_frequency import psd_multitaper

"""Power functions."""

# Author: Dmitrii Altukhov <dm-altukhov@ya.ru>
#         Annalisa Pascarella <a.pascarella@iac.cnr.it>




def _compute_and_save_psd(data_fname, fmin=0, fmax=120,
                          method='welch', is_epoched=False,
                          n_fft=256, n_overlap=0,
                          picks=None, proj=False, n_jobs=1, verbose=None):
    """Load epochs/raw from file, compute psd and save the result."""

    if is_epoched:
        epochs = read_epochs(data_fname)
    else:
        epochs = read_raw_fif(data_fname, preload=True)

    epochs_meg = epochs.pick_types(meg=True, eeg=False, eog=False, ecg=False)

    if method == 'welch':
        psds, freqs = psd_welch(epochs_meg, fmin=fmin, fmax=fmax)
    elif method == 'multitaper':
        psds, freqs = psd_multitaper(epochs_meg, fmin=fmin, fmax=fmax)
    else:
        raise Exception('nonexistent method for psd computation')


    _get_raw_array(data_fname, save_data=False)