コード例 #1
0
def load_stim_file(subject, args):
    stim_fname = op.join(
        MMVT_DIR, subject, 'electrodes',
        '{}{}.npz'.format(args.file_frefix, args.stim_channel))
    stim = np.load(stim_fname)
    labels, psd, time, freqs = (stim[k]
                                for k in ['labels', 'psd', 'time', 'freqs'])
    bipolar = '-' in labels[0]
    data = None
    freqs_dim = psd.shape.index(len(freqs))
    labels_dim = psd.shape.index(len(labels))
    if time.ndim > 0:
        time_dim = psd.shape.index(len(time))
    else:
        time_dim = next(iter(set(range(3)) - set([freqs_dim, labels_dim])))
    T, L, F = psd.shape[time_dim], psd.shape[labels_dim], psd.shape[freqs_dim]
    if args.downsample > 1:
        time = utils.downsample(time, args.downsample)
    colors = None
    conditions = []
    for freq_ind, (freq_from, freq_to) in enumerate(freqs):
        if data is None:
            # initialize the data matrix (electrodes_num x T x freqs_num)
            data = np.zeros((L, T, F))
        psd_slice = get_psd_freq_slice(psd, freq_ind, freqs_dim, time_dim)
        if args.downsample > 1:
            psd_slice = utils.downsample(psd_slice, args.downsample)
        data[:, :, freq_ind] = psd_slice
        data_min, data_max = utils.calc_min_max(psd_slice,
                                                norm_percs=args.norm_percs)
        if colors is None:
            colors = np.zeros((*data.shape, 3))
        for elec_ind, elec_name in enumerate(labels):
            elec_group = utils.elec_group(elec_name, bipolar)
            # if elec_group in ['LVF', 'RMT']:
            #     colors[elec_ind, :, freq_ind] = utils.mat_to_colors(psd_slice[elec_ind], data_min, data_max, colorsMap='BuGn')
            # else:
            colors[elec_ind, :,
                   freq_ind] = utils.mat_to_colors(psd_slice[elec_ind],
                                                   data_min,
                                                   data_max,
                                                   colorsMap=args.colors_map)
        conditions.append('{}-{}Hz'.format(freq_from, freq_to))
    output_fname = op.join(
        MMVT_DIR, subject, 'electrodes',
        'stim_electrodes_{}{}_{}.npz'.format(args.file_frefix,
                                             'bipolar' if bipolar else '',
                                             args.stim_channel))
    print('Saving {}'.format(output_fname))
    np.savez(output_fname,
             data=data,
             names=labels,
             conditions=conditions,
             colors=colors)
    return dict(data=data, labels=labels, conditions=conditions, colors=colors)
コード例 #2
0
def create_mmvt_file(subject,
                     stim_channel,
                     channel_list,
                     fs,
                     time,
                     stim,
                     theta,
                     downsample_ratio=10):
    theta -= np.min(theta)
    theta /= np.max(theta)
    theta *= -1
    stim = utils.downsample(stim.squeeze(), downsample_ratio)
    stim[stim >= 0.5] = 1
    stim[stim < 0.5] = 0
    theta = utils.downsample_2d(theta.T, downsample_ratio)
    data = np.vstack((stim, theta))
    data = data[:, :, np.newaxis]
    channel_list = [stim_channel] + channel_list
    meta_data_fname = op.join(MMVT_DIR, subject, 'electrodes',
                              'electrodes_bipolar_data.npz')
    np.savez(meta_data_fname,
             data=data,
             names=channel_list,
             conditions=['on'],
             dt=1 / fs)
コード例 #3
0
ファイル: stim.py プロジェクト: pelednoam/mmvt
def load_stim_file(subject, args):
    stim_fname = op.join(MMVT_DIR, subject, 'electrodes', '{}{}.npz'.format(
        args.file_frefix, args.stim_channel))
    stim = np.load(stim_fname)
    labels, psd, time, freqs = (stim[k] for k in ['labels', 'psd', 'time', 'freqs'])
    bipolar = '-' in labels[0]
    data = None
    freqs_dim = psd.shape.index(len(freqs))
    labels_dim = psd.shape.index(len(labels))
    if time.ndim > 0:
        time_dim = psd.shape.index(len(time))
    else:
        time_dim = next(iter(set(range(3)) - set([freqs_dim, labels_dim])))
    T, L, F = psd.shape[time_dim], psd.shape[labels_dim], psd.shape[freqs_dim]
    if args.downsample > 1:
        time = utils.downsample(time, args.downsample)
    colors = None
    conditions = []
    for freq_ind, (freq_from, freq_to) in enumerate(freqs):
        if data is None:
            # initialize the data matrix (electrodes_num x T x freqs_num)
            data = np.zeros((L, T, F))
        psd_slice = get_psd_freq_slice(psd, freq_ind, freqs_dim, time_dim)
        if args.downsample > 1:
            psd_slice = utils.downsample(psd_slice, args.downsample)
        data[:, :, freq_ind] = psd_slice
        data_min, data_max = utils.calc_min_max(psd_slice, norm_percs=args.norm_percs)
        if colors is None:
            colors = np.zeros((*data.shape, 3))
        for elec_ind, elec_name in enumerate(labels):
            elec_group = utils.elec_group(elec_name, bipolar)
            # if elec_group in ['LVF', 'RMT']:
            #     colors[elec_ind, :, freq_ind] = utils.mat_to_colors(psd_slice[elec_ind], data_min, data_max, colorsMap='BuGn')
            # else:
            colors[elec_ind, :, freq_ind] = utils.mat_to_colors(psd_slice[elec_ind], data_min, data_max, colorsMap=args.colors_map)
        conditions.append('{}-{}Hz'.format(freq_from, freq_to))
    output_fname = op.join(MMVT_DIR, subject, 'electrodes', 'stim_electrodes_{}{}_{}.npz'.format(
            args.file_frefix, 'bipolar' if bipolar else '', args.stim_channel))
    print('Saving {}'.format(output_fname))
    np.savez(output_fname, data=data, names=labels, conditions=conditions, colors=colors)
    return dict(data=data, labels=labels, conditions=conditions, colors=colors)
コード例 #4
0
def create_mmvt_file(subject,
                     stim_channel,
                     channel_list,
                     fs,
                     time,
                     stim,
                     theta,
                     downsample_ratio=10,
                     downsample_using_mean=True,
                     smooth_win_len=101):
    theta = utils.downsample_2d(theta.T, downsample_ratio,
                                downsample_using_mean)
    theta_smooth = np.zeros((theta.shape[0], theta.shape[1]))
    for k in range(theta.shape[0]):
        theta_smooth[k] = scipy.signal.savgol_filter(theta[k], smooth_win_len,
                                                     5)
        theta_smooth[k] -= np.min(theta_smooth[k])
        theta_smooth[k] /= np.max(theta_smooth[k])
    plt.plot(theta_smooth.T)
    plt.show()
    theta_smooth *= -1

    stim = utils.downsample(stim.squeeze(), downsample_ratio)
    stim[stim > 0] = 1
    stim_indices = np.where(np.diff(stim) == 1)[0] + 1
    print('{} stim!'.format(len(stim_indices)))
    plt.plot(stim)
    plt.show()

    data = np.vstack((stim, theta_smooth))
    data = data[:, :, np.newaxis]
    channel_list = [stim_channel] + channel_list
    meta_data_fname = op.join(MMVT_DIR, subject, 'electrodes',
                              'electrodes_bipolar_data.npz')
    np.savez(meta_data_fname,
             data=data,
             names=channel_list,
             conditions=['on'],
             dt=1 / fs)
コード例 #5
0
ファイル: plots.py プロジェクト: keshava/mmvt
def calc_cond_and_basline(subject,
                          con_method,
                          modality,
                          condition,
                          extract_mode,
                          band_name,
                          con_indentifer,
                          use_zvals,
                          node_names,
                          nodes_names_includes_hemi=False,
                          use_abs=True,
                          threshold=0.7,
                          window_length=25,
                          stc_downsample=2,
                          cond_name='interictals',
                          stc_subfolder='zvals',
                          stc_name=''):
    import mne
    from src.preproc import connectivity

    input_fname, baseline_fname = get_cond_and_baseline_fnames(
        subject, con_method, modality, condition, extract_mode, band_name,
        con_indentifer, use_zvals, cond_name)
    if not op.isfile(input_fname) or not op.isfile(baseline_fname):
        # print('Can\'t find {}'.format(input_fname))
        return None, None, None, None, None, None, None

    stcs_fol = op.join(MMVT_DIR, subject, 'meg', stc_subfolder)
    if stc_name == '':
        stc_name = '{}-epilepsy-dSPM-meg-{}-average-amplitude-zvals-rh.stc'.format(
            subject, condition)
    stc_fname = op.join(stcs_fol, stc_name)
    if op.isfile(stc_fname):
        stc = mne.read_source_estimate(stc_fname)
        times = utils.downsample(stc.times, stc_downsample)  # [window_length:]
        stc_data = np.max(stc.data, axis=0)
        stc_data = utils.downsample(stc_data,
                                    stc_downsample)  # [window_length:]
    else:
        stc_data, times = None, None

    d_cond, d_baseline = np.load(input_fname), np.load(baseline_fname)

    con_values1, con_values2 = fix_con_values(d_cond)
    con_values1, best_ords1 = connectivity.find_best_ord(con_values1,
                                                         return_ords=True)
    con_values2, best_ords2 = connectivity.find_best_ord(con_values2,
                                                         return_ords=True)
    # baseline_values1 = epi_utils.set_new_ords(d_baseline['con_values'], best_ords1)
    # baseline_values2 = epi_utils.set_new_ords(d_baseline['con_values2'], best_ords2)
    baseline_values1, baseline_values2 = fix_con_values(d_baseline)
    baseline_values1 = connectivity.find_best_ord(baseline_values1,
                                                  return_ords=False)
    baseline_values2 = connectivity.find_best_ord(baseline_values2,
                                                  return_ords=False)

    mask1 = epi_utils.filter_connections(
        con_values1,
        d_cond['con_names'],
        threshold,
        node_names,
        '',
        use_abs,
        nodes_names_includes_hemi=nodes_names_includes_hemi)
    mask2 = epi_utils.filter_connections(
        con_values2,
        d_cond['con_names2'],
        threshold,
        node_names,
        '',
        use_abs,
        nodes_names_includes_hemi=nodes_names_includes_hemi)
    names = np.concatenate(
        (d_cond['con_names'][mask1], d_cond['con_names2'][mask2]))
    if len(names) == 0:
        print('{} no connections'.format(condition))
        return None, None, None, None, None, None, None

    x_cond = np.concatenate((con_values1[mask1], con_values2[mask2]))
    x_baseline = np.concatenate(
        (baseline_values1[mask1], baseline_values2[mask2]))
    if best_ords1 is not None and best_ords2 is not None:
        best_ords = np.concatenate((best_ords1[mask1], best_ords2[mask2]))
        names = [
            '{} {}'.format(name, int(best_ord))
            for name, best_ord in zip(names, best_ords)
        ]
    return d_cond, d_baseline, x_cond, x_baseline, names, stc_data, times
コード例 #6
0
ファイル: utils.py プロジェクト: bdthombre/mmvt
def get_window_times(window_fname, downsample=2):
    evoked = mne.read_evokeds(window_fname)[0]
    times = evoked.times if len(evoked.times) % downsample == 0 else \
        evoked.times[:-(downsample - 1)]
    return utils.downsample(times, downsample)
コード例 #7
0
def plot_modalities_power_spectrums_with_graph(subject,
                                               modalities,
                                               window_fname,
                                               figure_name='',
                                               percentiles=[5, 95],
                                               inverse_method='dSPM',
                                               ylims=[-18, 6],
                                               file_type='jpg',
                                               cb_ticks=[],
                                               cb_ticks_font_size=12,
                                               figure_fol=''):

    evoked = mne.read_evokeds(window_fname)[0]
    times = evoked.times if len(evoked.times) % 2 == 0 else evoked.times[:-1]
    times = utils.downsample(times, 2)
    min_t, max_t = round(times[0]), round(times[-1])
    freqs = np.concatenate(
        [np.arange(1, 30),
         np.arange(31, 60, 3),
         np.arange(60, 125, 5)])
    # bands = dict(delta=[1, 4], theta=[4, 8], alpha=[8, 15], beta=[15, 30], gamma=[30, 55], high_gamma=[65, 120])
    bands = dict(delta=[1, 4], high_gamma=[65, 120])
    if figure_fol == '':
        figure_fol = op.join(MMVT_DIR, subject, 'epilepsy-figures',
                             'power-spectrum')

    fig, ax = plt.subplots(3, len(modalities), figsize=(20, 10))
    for ind, modality in enumerate(modalities):
        powers_ax = ax[0, ind]
        powers_ax.set_title(modality.upper(), fontdict={'fontsize': 18})
        positive_powers_ax = ax[1, ind]
        negative_powers_ax = ax[2, ind]
        root_dir = op.join(EEG_DIR if modality == 'eeg' else MEG_DIR, subject)
        output_fname = op.join(
            root_dir, '{}-epilepsy-{}-{}-{}-induced_norm_power.npz'.format(
                subject, inverse_method, modality, '{window}'))
        window = utils.namebase(window_fname)
        window_output_fname = output_fname.format(window=window)
        d = np.load(window_output_fname)
        powers_negative, powers_positive = epi_utils.calc_masked_negative_and_positive_powers(
            d['min'], d['max'], percentiles)

        im1 = _plot_powers(powers_negative, powers_ax, times, freqs)
        im2 = _plot_powers(powers_positive, powers_ax, times, freqs)
        if ind == 0:
            powers_ax.set_ylabel('Frequency (Hz)')
        else:
            powers_ax.set_yticks([])
            add_colorbar(powers_ax, im2, cb_ticks, cb_ticks_font_size)

        # for powers, axis, positive in zip([powers_positive, powers_negative], ax[1:2, ind], [True, False]):
        #     for band_name, band_freqs in bands.items():
        #         idx = [k for k, f in enumerate(freqs) if band_freqs[0] <= f <= band_freqs[1]]
        #         band_power = np.mean(powers[idx, :], axis=0)
        #         band_power[abs(band_power) < 2] = 0
        #         axis.plot(times, band_power.T, label=band_name)
        #     axis.set_xlim([min_t, max_t])
        #     axis.set_ylim([2, ylims[1]] if positive else [ylims[0], -2])
        #     if ind == 0:
        #         axis.set_ylabel('Positive Z-Scores' if positive else 'Negative Z-Scores')
        #     else:
        #         axis.set_yticks([])
        #         axis.legend(loc='center left', bbox_to_anchor=(1, 0.5))
        # negative_powers_ax.set_xlabel('Time (s)')

        for band_name, band_freqs in bands.items():
            idx = [
                k for k, f in enumerate(freqs)
                if band_freqs[0] <= f <= band_freqs[1]
            ]
            band_power = np.mean(powers_negative[idx, :], axis=0)
            band_power[abs(band_power) < 2] = 0
            positive_powers_ax.plot(times,
                                    band_power.T,
                                    label=band_name.replace('_', ' '))
        positive_powers_ax.set_xlim([min_t, max_t])
        positive_powers_ax.set_ylim([2, ylims[1]])
        if ind == 0:
            positive_powers_ax.set_ylabel('Positive Z-Scores')
        else:
            positive_powers_ax.set_yticks([])
        if ind == len(modalities) - 1:
            add_legend(positive_powers_ax)

        for band_name, band_freqs in bands.items():
            idx = [
                k for k, f in enumerate(freqs)
                if band_freqs[0] <= f <= band_freqs[1]
            ]
            band_power = np.mean(powers_positive[idx, :], axis=0)
            band_power[abs(band_power) < 2] = 0
            negative_powers_ax.plot(times,
                                    band_power.T,
                                    label=band_name.replace('_', ' '))
        negative_powers_ax.set_xlim([min_t, max_t])
        negative_powers_ax.set_ylim([ylims[0], -2])
        if ind == 0:
            negative_powers_ax.set_ylabel('Negative Z-Scores')
        else:
            negative_powers_ax.set_yticks([])
        if ind == len(modalities) - 1:
            add_legend(negative_powers_ax)
        negative_powers_ax.set_xlabel('Time (s)')

    plt.tight_layout()
    plt.subplots_adjust(left=None,
                        bottom=None,
                        right=0.92,
                        top=None,
                        wspace=None,
                        hspace=None)
    if figure_name != '':
        plt.savefig(op.join(figure_fol, '{}.{}'.format(figure_name,
                                                       file_type)),
                    dpi=300)
        plt.close()
    else:
        plt.show()