Example #1
1
    def plot_topo(self, i_clu=None, pos=None, **kwargs):
        """
        Plots fmap of one or several clusters.

        Parameters
        ----------
        i_clu : int
            cluster index

        Can take evoked.plot_topomap() parameters.

        Returns
        -------
        fig
        """
        from mne import find_layout
        from mne.viz import plot_topomap

        # Channel positions
        pos = find_layout(self.info).pos
        # create topomap mask from sig cluster
        mask, space_inds, time_inds = self._get_mask(i_clu)

        if pos is None:
            pos = find_layout(self.info).pos

        # plot average test statistic and mark significant sensors
        topo = self.T_obs_[time_inds, :].mean(axis=0)
        fig = plot_topomap(topo, pos, **kwargs)

        return fig
Example #2
1
    def update_figure(self, data, pos=None, names=None, show_names=None, show_colorbar=True, central_text=None,
                      right_bottom_text=None, show_not_found_symbol=False, montage=None):
        if montage is None:
            if pos is None:
                pos = ch_names_to_2d_pos(names)
        else:
            pos = montage.get_pos('EEG')
            names = montage.get_names('EEG')
        data = np.array(data)
        self.axes.clear()
        if self.colorbar:
            self.colorbar.remove()
        if show_names is None:
            show_names = ['O1', 'O2', 'CZ', 'T3', 'T4', 'T7', 'T8', 'FP1', 'FP2']
        show_names = [name.upper() for name in show_names]
        mask = np.array([name.upper() in show_names for name in names]) if names else None
        v_min, v_max = None, None
        if (data == data[0]).all():
            data[0] += 0.1
            data[1] -= 0.1
            v_min, v_max = -1, 1
        a, b = plot_topomap(data, pos, axes=self.axes, show=False, contours=0, names=names, show_names=True,
                            mask=mask,
                            mask_params=dict(marker='o',
                                             markerfacecolor='w',
                                             markeredgecolor='w',
                                             linewidth=0,
                                             markersize=3),
                            vmin=v_min,
                            vmax=v_max)
        if central_text is not None:
            self.axes.text(0, 0, central_text, horizontalalignment='center', verticalalignment='center')

        if right_bottom_text is not None:
            self.axes.text(-0.65, 0.65, right_bottom_text, horizontalalignment='left', verticalalignment='top')

        if show_not_found_symbol:
            self.axes.text(0, 0, '/', horizontalalignment='center', verticalalignment='center')
            self.axes.text(0, 0, 'O', size=10, horizontalalignment='center', verticalalignment='center')

        if show_colorbar:
            self.colorbar = self.fig.colorbar(a, orientation='horizontal', ax=self.axes)
            self.colorbar.ax.tick_params(labelsize=6)
            self.colorbar.ax.set_xticklabels(self.colorbar.ax.get_xticklabels(), rotation=90)
        self.draw()
Example #3
1
def visualise(exp_num,main_title,*args):
    layout = find_layout(info, ch_type='grad')
    number_of_heads = len(args)
    tmp = [list(l) for l in zip(*args)]
    titles = tmp[0]
    data = tmp[1]
    max_row_lenght = 5 #depends from monitor length (:
    fig,axes=plt.subplots(-(-number_of_heads//max_row_lenght),min(max_row_lenght,number_of_heads),figsize=(20, 20))
    fig.suptitle(main_title, fontsize=14)
    min_value = np.array(map(lambda x:x.min(),data)).min()
    max_value = np.array(map(lambda x:x.max(),data)).max()
    for i in range(number_of_heads):
        axes[np.unravel_index(i,axes.shape)].set_title(titles[i])
        if data[i].any():
            im,_ = plot_topomap(data[i],layout.pos,axes=axes[np.unravel_index(i,axes.shape)],
                                vmin=min_value,vmax=max_value,show=False)
    fig.colorbar(im,ax=axes.ravel().tolist(),shrink=0.3,fraction=0.025)
    save_fig(exp_num,main_title,fig)
Example #4
0
def _plot_legend_topomap(win, ax, channel_picked):
    """Plot the little topomap legend for the PSD plot."""
    from mne.viz import plot_topomap
    import numpy as np
    from matplotlib.colors import ListedColormap

    white = np.array([[0, 0, 0, 0]])
    cmp = ListedColormap(white)

    try:
        obj = win.psd
    except AttributeError:
        obj = win.avg

    zeros = [0 for i in range(len(obj.pos))]
    mask = np.array([False for i in range(len(obj.pos))])
    mask[obj.with_coord.index(channel_picked - 1)] = True

    plot_topomap(zeros,
                 obj.pos,
                 axes=ax,
                 cmap=cmp,
                 mask=mask,
                 show=False,
                 mask_params=dict(marker='.',
                                  markersize=18,
                                  markerfacecolor='black',
                                  markeredgecolor='black'),
                 outlines='skirt')
Example #5
0
 def plot_noise_topo(self, pick_types='mag'):
     picks = mne.pick_types(self.info, meg=pick_types)
     f, axes = plt.subplots(2, 5)
     powers = np.sqrt(self.sigmas) * self.normalization
     for j, ax in enumerate(axes.ravel()):
         f_idx = int(len(self.freqs) / 10)
         power = powers[f_idx, picks]
         plot_topomap()
Example #6
0
def plot_grads(data, info):
    names = [info["chs"][i]["ch_name"] for i in range(len(info["chs"]))]
    av_data = data.reshape(-1, 2).mean(axis=1)
    print(av_data.shape)
    av_names = [n[:-1] for n in names[::2]]
    layout = find_layout(info)
    pos = layout.pos[::2, :2]
    plot_topomap(av_data, pos, names=av_names, show_names=True)
Example #7
0
def _plot_glm_contrast_topo(inst, contrast, figsize=(12, 7), sphere=None):

    info = deepcopy(inst if isinstance(inst, Info) else inst.info)

    # Extract types. One subplot is created per type (hbo/hbr)
    types = np.unique(_get_channel_types(info))

    # Extract values to plot and rescale to uM
    estimates = contrast.effect[0]
    estimates = estimates * 1e6

    # Create subplots for figures
    fig, axes = plt.subplots(nrows=1, ncols=len(types), figsize=figsize)
    # Create limits for colorbar
    vmax = np.max(np.abs(estimates))
    vmin = vmax * -1.
    cmap = mpl.cm.RdBu_r
    norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

    for t_idx, t in enumerate(types):

        estmrg, pos, chs, sphere = _handle_overlaps(info, t, sphere, estimates)

        # Deal with case when only a single chroma is available
        if len(types) == 1:
            ax = axes
        else:
            ax = axes[t_idx]

        # Plot the topomap
        plot_topomap(estmrg,
                     pos,
                     extrapolate='local',
                     names=chs,
                     vmin=vmin,
                     vmax=vmax,
                     cmap=cmap,
                     axes=ax,
                     show=False,
                     sphere=sphere)
        # Sets axes title
        if t == 'hbo':
            ax.set_title('Oxyhaemoglobin')
        elif t == 'hbr':
            ax.set_title('Deoxyhaemoglobin')
        else:
            ax.set_title(t)

    # Create a single colorbar for all types based on limits above
    ax1_divider = make_axes_locatable(ax)
    cax1 = ax1_divider.append_axes("right", size="7%", pad="2%")
    cbar = mpl.colorbar.ColorbarBase(cax1,
                                     cmap=cmap,
                                     norm=norm,
                                     orientation='vertical')
    cbar.set_label('Contrast Effect', rotation=270)

    return fig
Example #8
0
def plot_weights_for_model(all_weights, subject_file_data):
    loc_xy = extract_2D_channel_location(subject_file_data)
    # print vals[0,0,0,:].shape

    for i, val in enumerate(all_weights):
        plt.subplot(3, 4, i)
        plot_topomap(val,np.fliplr(loc_xy),show=False)
    plt.show()
    print "done"
Example #9
0
    def plot_topography(self, info, stimulus_feature=None):
        try:
            from mne.viz import plot_topomap
        except ImportError:
            print("Topographical plots require MNE-Python!")

        if stimulus_feature is None:
            weights = self.weights.mean(axis=0)
        else:
            weights = self.weights[stimulus_feature, :, :]
        plot_topomap(weights, info)
Example #10
0
def my_topomap(dat, chans, mask=None, clim=None):

    pos = get_channel_pos(chans)
    if clim == None:
        im = plot_topomap(dat, pos, mask=mask, outlines="head")
    else:
        im = plot_topomap(dat,
                          pos,
                          mask=mask,
                          outlines="head",
                          vmin=clim[0],
                          vmax=clim[1])

    plt.colorbar(im[0])
def create_topo(data, fig_title, ax, v_min=-0.022, v_max=0.022):
    from mne.viz import plot_topomap

    mask = np.array([True for ch in EEG_channels])

    locations = pd.read_csv('./channel_2d_location.csv', index_col=0)
    locations['ch'] = locations.index.map(renameChannels)
    locations = locations.set_index('ch')
    locations = locations.loc[EEG_channels]
    # locations = locations.drop(index=["PO8", "PO7"])

    mask_params = dict(marker='o',
                       markerfacecolor='w',
                       markeredgecolor='k',
                       linewidth=0,
                       markersize=10)

    print("{:} Data max {:0.3f} Data min {:0.3f}".format(
        fig_title, data.max(), data.min()))

    im, cn = plot_topomap(data.values,
                          locations[['x', 'y']].values,
                          outlines='head',
                          axes=ax,
                          cmap='jet',
                          show=False,
                          names=EEG_channels,
                          show_names=True,
                          mask=mask,
                          mask_params=mask_params,
                          vmin=v_min,
                          vmax=v_max,
                          contours=7)
    ax.set_title(fig_title, fontsize=10)
    return im
Example #12
0
    def plot_avg_topomap_band(self,
                              freq_index_min,
                              freq_index_max,
                              vmin=None,
                              vmax=None,
                              show_names=False,
                              log_display=False,
                              axes=None):
        """
        Plot the map of the average power for a given frequency band chosen
        by freq_index_min and freq_index_max, the frequency is hence the value
        self.freqs[freq_index]. This function will return an error if the
        class is not initialized with the coordinates of the different
        electrodes.
        """
        from mne.viz import plot_topomap

        psd_values = self.data[:, self.with_coord,
                               freq_index_min:freq_index_max]
        psd_mean = mean(psd_values, axis=2)  # average over frequency band
        psd_mean = mean(psd_mean, axis=0)  # average over epochs
        if log_display:
            psd_mean = 10 * log(psd_mean)
        return plot_topomap(psd_mean,
                            self.pos,
                            axes=axes,
                            vmin=vmin,
                            vmax=vmax,
                            show=False,
                            cmap=self.cmap,
                            head_pos=self.head_pos,
                            outlines='skirt',
                            contours=3)
Example #13
0
    def plot_topo(self, i_clu=None, pos=None, **kwargs):
        """
        Plots fmap of one or several clusters.

        Parameters
        ----------
        i_clu : int
            cluster index

        Can take evoked.plot_topomap() parameters.

        Returns
        -------
        fig
        """
        from mne import find_layout
        from mne.viz import plot_topomap

        # Channel positions
        pos = find_layout(self.info).pos
        # create topomap mask from sig cluster
        mask, space_inds, time_inds = self._get_mask(i_clu)

        if pos is None:
            pos = find_layout(self.info).pos

        # plot average test statistic and mark significant sensors
        topo = self.T_obs_[time_inds, :].mean(axis=0)
        fig = plot_topomap(topo, pos, **kwargs)

        return fig
Example #14
0
    def plot_topomap_band(self,
                          freq_index_min,
                          freq_index_max,
                          vmin=None,
                          vmax=None,
                          axes=None,
                          log_display=False):
        """
        Plot the map of the power for a given frequency band chosen by
        freq_index_min and freq_index_max, the frequency is hence the value
        self.freqs[freq_index]. This function will return an error if the
        class is not initialized with the coordinates of the different
        electrodes.
        """
        from mne.viz import plot_topomap
        from numpy import mean

        psd_mean = mean(self.data[self.with_coord,
                                  freq_index_min:freq_index_max],
                        axis=1)
        if log_display:
            psd_mean = 10 * log(psd_mean)
        return plot_topomap(psd_mean,
                            self.pos,
                            axes=axes,
                            vmin=vmin,
                            vmax=vmax,
                            show=False,
                            cmap=self.cmap,
                            head_pos=self.head_pos)
Example #15
0
 def topo_kernel(self, layer_name):
     layer_name = self._check_layer_name(layer_name)
     plt.rcParams['font.size'] = 9
     for name in layer_name:
         _weights = self.layer_dict[name].get_weights()[0]
         print(_weights.shape)
         _min = np.min(_weights)
         _max = np.max(_weights)
         n = 1
         fig, axs = plt.subplots()
         for i in range(_weights.shape[-2]):
             for j in range(_weights.shape[-1]):
                 ax = plt.subplot(
                     _weights.shape[-2] * _weights.shape[-1] // 20, 20, n)
                 im, cn = viz.plot_topomap(
                     np.squeeze(_weights[:, :, i, j]),
                     self.locs,
                     vmin=_min,
                     vmax=_max,
                     names=self.sensors_name,
                     show_names=True,
                     show=False,
                     image_interp='bicubic',
                     extrapolate='head',
                     sphere=(0, 0, 0, 1))  # draw topographic image
                 if n <= 20:
                     ax.spines['bottom'].set_position(('axes', 1.2))
                     if n <= 10:
                         ax.set_xlabel(n, fontsize=12)
                     else:
                         ax.set_xlabel(n - 10, fontsize=12)
                 if n % 20 == 1:
                     ax.spines['left'].set_position(('axes', 0.07))
                     ax.set_ylabel(chr(ord('a') + n // 10), fontsize=12)
                 if n % 20 == 0:
                     ax.spines['left'].set_position(('axes', 1.22))
                     ax.set_ylabel(chr(ord('a') - 1 + n // 10), fontsize=12)
                 n += 1
         divider = make_axes_locatable(axs)
         cax = divider.append_axes('bottom', size='1%', pad=0.6)
         cb = fig.colorbar(im,
                           cax=cax,
                           orientation='horizontal',
                           ticklocation='top')
         plt.tight_layout(pad=0)
         plt.subplots_adjust(right=0.99,
                             left=0.01,
                             top=1,
                             bottom=0,
                             wspace=0,
                             hspace=0)
         plt.margins(0, 0)
         fig.savefig(os.path.join('topo_kernel.png'),
                     format='png',
                     transparent=False,
                     dpi=300,
                     pad_inches=0)
         plt.show(block=False)
Example #16
0
 def fs_class_topo_kernel(self, layer_name):
     layer_name = self._check_layer_name(layer_name)
     class_data = self._class_data(self.data)
     _input = self.model.input
     _output = self.model.output
     plt.rcParams['font.size'] = 12
     for name in layer_name:
         layer = self.layer_dict[name]
         _weights = layer.get_weights()[0]
         layer_model = tf.keras.Model([_input],
                                      [layer.input, layer.output, _output])
         fig = plt.figure()
         for c in class_data:
             with tf.GradientTape() as g:
                 conv_input, conv_output, Pred = layer_model(
                     class_data[c]['x'])
                 prob = Pred[:, c]
                 grads = g.gradient(prob, conv_output)
                 pooled_grads = K.sum(grads, axis=(0, 1, 2))
                 pooled_grads = tf.reshape(pooled_grads,
                                           shape=(_weights.shape[-2],
                                                  _weights.shape[-1]))
             s_weights = tf.reduce_mean(tf.abs(
                 tf.multiply(pooled_grads, _weights)),
                                        axis=(1, 2, 3))
             ax = fig.add_subplot(2, 2, c + 1)
             ax.set_xlabel('({}) {}'.format(chr(c + 97),
                                            self.class_names[c]))
             viz.plot_topomap(np.array(s_weights),
                              self.locs,
                              names=self.sensors_name,
                              show_names=True,
                              show=False,
                              image_interp='bicubic',
                              cmap='Spectral_r',
                              extrapolate='head',
                              sphere=(0, 0, 0, 1))  # draw topographic image
         plt.tight_layout(pad=0)
         plt.margins(0, 0)
         fig.savefig(os.path.join('fs_class_topo_kernel.png'),
                     format='png',
                     transparent=False,
                     dpi=300,
                     pad_inches=0)
         plt.show(block=False)
Example #17
0
def gen_topomap_frames(data, times_index_to_plot, pos, title, cmap='PuBu'):
    # create OpenCV video writer

    bandpower_over_time_index = data.index

    frames = []

    cNorm = mpl.colors.Normalize(vmin=data.min().min(), vmax=data.max().max())
    sm = cm.ScalarMappable(norm=cNorm, cmap=cmap)

    # loop over your images
    for idx, time_index in enumerate(times_index_to_plot):
        fig, axs = plt.subplots(nrows=1, ncols=1, figsize=(10, 10))
        viz.plot_topomap(data.iloc[time_index, :].T.values,
                         cmap=cmap,
                         sphere=1.,
                         pos=pos,
                         axes=axs,
                         sensors=False,
                         show_names=True,
                         show=False,
                         names=data.columns)

        plt.title(
            f"{title}: {index_to_time(times_index_to_plot[idx], bandpower_over_time_index)}"
        )

        #cax = fig.add_axes([1.01, 0.2, 0.05, 0.5])
        # notice that this will create some weird plot if you plot it interactively... no idea why
        fig.colorbar(sm, ax=axs, orientation='vertical')

        plt.tight_layout()

        # this has to be the last thing
        fig.canvas.draw()

        mat = np.array(fig.canvas.renderer._renderer)
        #mat = cv2.cvtColor(mat, cv2.COLOR_RGB2BGR)

        frames.append(mat)

        plt.close()

    return frames
Example #18
0
def Topoplot_DA(DA=None,
                sensors_pos=None,
                masked=False,
                chance_level=0.05,
                Da_perm=None,
                Da_bino=None,
                figures_save_file=None,
                show_fig=False):
    if masked == True:
        mask_default = np.full((len(DA)), False, dtype=bool)
        mask = np.array(mask_default)
        if Da_perm is not None:
            nperm = Da_perm.shape[0]
            indx_chance = int(nperm - chance_level * nperm)
            daperm = np.sort(Da_perm, axis=0)
            mask[DA >= np.amax(daperm[indx_chance - 2, :])] = True
        if Da_bino is not None:
            mask[DA >= Da_bino] = True

        mask_params = dict(marker='*', markerfacecolor='w', markersize=15)
        fig1 = plt.figure(figsize=(10, 15))
        ax1, _ = plot_topomap(DA,
                              sensors_pos,
                              cmap='inferno',
                              show=show_fig,
                              vmin=0,
                              vmax=100,
                              mask=mask,
                              mask_params=mask_params,
                              outlines='skirt')
        #names=elect,show_names=True)
    elif masked == False:

        fig1 = plt.figure(figsize=(10, 15))
        ax1, _ = plot_topomap(DA,
                              sensors_pos,
                              cmap='inferno',
                              show=show_fig,
                              vmin=0,
                              vmax=100,
                              outlines='skirt')

    if figures_save_file is not None:
        plt.savefig(figures_save_file, dpi=300)
Example #19
0
def headplot(effects):
    pos = [[173, 52], [211, 48], [250, 50], [86, 95], [149, 120], [211, 124],
           [272, 121], [335, 94], [99, 153], [322, 152], [58, 203], [133, 203],
           [210, 200], [288, 202], [100, 246], [320, 250], [406,
                                                            221], [86, 307],
           [150, 280], [210, 280], [270, 280], [337, 306], [142, 328],
           [281, 326], [173, 354], [212, 355], [247, 352]]
    Names = [
        'FP1', 'FPZ', 'FP2', 'F7', 'F3', 'Fz', 'F4', 'F8', 'Fc5', 'Fc6', 'T7',
        'C3', 'Cz', 'C4', 'T8', 'CP6', 'A2', 'P7', 'P3', 'Pz', 'P4', 'P8',
        'Po5', 'Po6', 'O1', 'Oz', 'O2'
    ]
    mypos = np.array(pos, ndmin=2)
    mv.plot_topomap(effects,
                    mypos,
                    cmap='RdBu_r',
                    names=Names,
                    show_names=True)
    return (mv)
Example #20
0
def _plot_atom(Dk, info, ax, color, plot="atom"):
    sfreq = info.get('sfreq', 1)
    n_channels = info.get('n_channels')
    if plot == "atom":
        t = np.arange(len(Dk) - n_channels) / sfreq
        ax.plot(t, Dk[n_channels:], c=color)
    elif plot == "topo":
        # We can import mne here as we already checked that mne was installed
        from mne.viz import plot_topomap
        plot_topomap(Dk[:info['n_channels']], info, axes=ax, show=False)
    elif plot == "psd":
        psd = np.abs(np.fft.rfft(Dk[info['n_channels']:]))**2
        frequencies = np.linspace(0, sfreq / 2.0, len(psd))
        ax.plot(frequencies, psd, color=color)
        # ax.set(xlabel='Frequencies (Hz)', title='PSD atom final')
        ax.grid(True)
        ax.set_xlim(0, 30)
    else:
        raise NotImplementedError("No plot '{}' for atom".format(plot))
Example #21
0
def save_viz_scnn(args, activations, model):

    layer_dict, conv_dict, spat_dict, temp_dict, spatial_out, out_layer = _parse_layers(
        model)

    chans = np.load(args.chans.open('rb'))

    if args.maximize:
        topomaps = activations[spatial_out.name]
        for i in range(topomaps.shape[-1]):
            im, cn = plot_topomap(topomaps[..., i], chans, show=True)
            save_loc = args.save_viz / spatial_out.name
            save_loc.mkdir(parents=True, exist_ok=True)
            # plt.title('Spatial Component {0}'.format(i))
            plt.colorbar()
            plt.savefig(str(save_loc / 'component_{0}.png'.format(i)))
            plt.clf()

        for t in temp_dict:
            fil_act = activations[t]
            for f in range(fil_act.shape[-1]):
                for c in range(fil_act.shape[-2]):
                    directory = args.save_viz / t / 'filter_{0}'.format(f)
                    directory.mkdir(parents=True, exist_ok=True)
                    plt.specgram(fil_act[..., c, f].squeeze(),
                                 Fs=200,
                                 cmap='bwr',
                                 NFFT=64,
                                 noverlap=50)
                    plt.colorbar()
                    plt.title('{0} {1} Component {2}'.format(t, f, c))
                    plt.savefig(str(directory / 'component_{0}'.format(c)))
                    plt.clf()

    if out_layer is not None:
        out_act = activations[out_layer.name]
        for c in range(out_act.shape[-1]):
            for f in range(out_act.shape[-2]):
                directory = args.save_viz / 'OUT' / 'class_{0}'.format(c)
                directory.mkdir(parents=True, exist_ok=True)
                plt.specgram(out_act[..., f, c].squeeze(),
                             Fs=200,
                             cmap='bwr',
                             NFFT=64,
                             noverlap=50)
                plt.colorbar()
                classes = ['<10', '>=10']
                plt.title('Output Class {0} Component {1}'.format(
                    classes[c], f))
                plt.ylabel('Frequency (Hz)')
                plt.xlabel('Time (s)')
                plt.savefig(str(directory / 'component_{0}'.format(f)))
                plt.clf()
Example #22
0
def visualise(t_data, p_data, sensor_type, freq):
    #reseives t-values (and optionaly p-values) as vectors [channel x 1]
    layout = find_layout(info, ch_type=sensor_type.lower())
    im, _ = plot_topomap(data=t_data,
                         pos=layout.pos,
                         show=False,
                         vmin=-4.5,
                         vmax=4.5)
    plt.colorbar(im)
    title = 'fq=%d_min_p=%0.4f' % (freq, p_data.min())
    plt.title(title)
    return title
def Topo_DA(DA=[], sensors_pos=[], mask=False, DA_thr=None, save_file=None):
    if mask:
        mask_default = np.full((len(DA)), False, dtype=bool)
        mask = np.array(mask_default)
        mask[DA >= DA_thr] = True
        mask_params = dict(marker='*', markerfacecolor='w',
                           markersize=18)  # significant sensors appearence
        fig = plt.figure(figsize=(10, 5))
        ax, _ = plot_topomap(DA,
                             sensors_pos,
                             cmap='viridis',
                             show=False,
                             extrapolate='local',
                             vmin=50,
                             vmax=70,
                             contours=True,
                             mask=mask,
                             mask_params=mask_params)

        #fig.colorbar(ax, shrink=0.25)
        if save_file:
            plt.savefig(save_file, dpi=300)

    else:
        fig = plt.figure(figsize=(10, 5))
        ax, _ = plot_topomap(DA,
                             sensors_pos,
                             cmap='viridis',
                             show=False,
                             vmin=50,
                             vmax=70,
                             contours=True)

        #fig.colorbar(ax, shrink=0.25)
        if save_file:
            plt.savefig(save_file, dpi=300)
    return ax
Example #24
0
    def plot_topomap(self, freq_index, axes=None, log_display=False):
        """
        Plot the map of the power for a given frequency chosen by freq_index,
        the frequency is hence the value self.freqs[freq_index]. This function
        will return an error if the class is not initialized with the
        coordinates of the different electrodes.
        """
        from mne.viz import plot_topomap

        psd_values = self.data[self.with_coord, freq_index]
        if log_display:
            psd_values = 10 * log(psd_values)
        return plot_topomap(psd_values, self.pos, axes=axes,
                            show=False, cmap=self.cmap,
                            head_pos=self.head_pos)
Example #25
0
    def update_figure(self, data, pos=None, names=None, show_names=None, show_colorbar=True, central_text=None,
                      right_bottom_text=None, show_not_found_symbol=False, montage=None):
        if montage is None:
            if pos is None:
                pos = ch_names_to_2d_pos(names)
        else:
            pos = montage.get_pos('EEG')
            names = montage.get_names('EEG')
        data = np.array(data)
        self.axes.clear()
        if self.colorbar:
            self.colorbar.remove()
        if show_names is None:
            show_names = ['O1', 'O2', 'CZ', 'T3', 'T4', 'T7', 'T8', 'FP1', 'FP2']
        show_names = [name.upper() for name in show_names]
        mask = np.array([name.upper() in show_names for name in names]) if names else None
        v_min, v_max = None, None
        if (data == data[0]).all():
            data[0] += 0.1
            data[1] -= 0.1
            v_min, v_max = -1, 1
        a, b = plot_topomap(data, pos, axes=self.axes, show=False, contours=0, names=names, show_names=True,
                            mask=mask,
                            mask_params=dict(marker='o',
                                             markerfacecolor='w',
                                             markeredgecolor='w',
                                             linewidth=0,
                                             markersize=3),
                            vmin=v_min,
                            vmax=v_max)
        if central_text is not None:
            self.axes.text(0, 0, central_text, horizontalalignment='center', verticalalignment='center')

        if right_bottom_text is not None:
            self.axes.text(-0.65, 0.65, right_bottom_text, horizontalalignment='left', verticalalignment='top')

        if show_not_found_symbol:
            self.axes.text(0, 0, '/', horizontalalignment='center', verticalalignment='center')
            self.axes.text(0, 0, 'O', size=10, horizontalalignment='center', verticalalignment='center')

        if show_colorbar:
            self.colorbar = self.fig.colorbar(a, orientation='horizontal', ax=self.axes)
            self.colorbar.ax.tick_params(labelsize=6)
            self.colorbar.ax.set_xticklabels(self.colorbar.ax.get_xticklabels(), rotation=90)
        self.draw()
Example #26
0
 def visualise_convs_on_mne_topomap(self, convs):
     # This function used to test correctness of finded convolutions
     test_conv = './test_conv'
     if not os.path.isdir(test_conv):
         os.makedirs(test_conv)
     for conv_index, conv in enumerate(convs):
         fake_data = np.zeros(self.num_channels)
         fake_data[conv] = 100
         conv_names = [self.ch_names[index] for index in conv]
         title = '_'.join([name for name in conv_names])
         plt.title('%s' % (title))
         im, _ = plot_topomap(data=fake_data,
                              pos=self.topography_2D,
                              contours=0,
                              names=self.ch_names,
                              show=False)
         plt.savefig(os.path.join(test_conv, title + '.png'))
         plt.close()
Example #27
0
 def plot_topomap(self, output, pot_signal, pos):
     from mne.viz import plot_topomap
     import matplotlib.pyplot as plt
     minn = min(pot_signal)
     maxx = max(pot_signal)
     plt.title('topomap')
     fig = plot_topomap(pot_signal,
                        pos,
                        cmap='jet',
                        sensors='k.',
                        contours=0,
                        image_interp='spline36',
                        show=False,
                        vmin=minn,
                        vmax=maxx)
     plt.savefig(output)
     plt.show(fig)
     return fig
Example #28
0
    with h5py.File('{}\\{}\\{}'.format(settings['dir'], experiment, 'experiment_data.h5')) as f:
        fs, channels, p_names = get_info(f, settings['drop_channels'])
        rejection, alpha, ica = None, None, None#load_rejections(f, reject_alpha=True)
        odict = OrderedDict()
        for j, name in enumerate(p_names):
            x = preproc(f['protocol{}/raw_data'.format(j + 1)][:], fs, rejection if reject else None)
            odict = add_data_simple(odict, name, x)
        raw[names[j_experiment]] = odict


    for j, key in enumerate(state_plot):

        f, Pxx = welch(raw[names[j_experiment]][key], fs, nperseg=2048, axis=0)
        #axes[j].semilogy(f, Pxx, alpha=1, c=cm[j_experiment*2+3])
        ax = axes[j, j_experiment]
        a, b = plot_topomap(np.log10(Pxx[np.argmin(np.abs(f-peak)), :]), ch_names_to_2d_pos(channels), cmap='Reds',
                            axes=ax, show=False, vmax=-10.5, vmin=-13)
        if j_experiment == 0:
            ax.set_ylabel(key)
        if j == len(state_plot)-1:
            ax.set_xlabel(names[j_experiment])

        #axes[j].set_xlim(0, 250)
        #axes[j].set_ylim(1e-19, 5e-10)
            #x_plot = np.abs(hilbert(fft_filter(raw_before[key][:, channels.index(ch)], fs)))
            #leg.append('P={:.3f}, D={:.3f}s'.format(Pxx[(f > 9) & (f < 14)].mean(), sum((x_plot > 5)) / fs/2))
        #axes[j].legend(leg)


fig2.colorbar(a)
plt.show()
Example #29
0
            fs, channels, p_names = get_info(f, settings['drop_channels'])
            rejection, alpha, ica = load_rejections(f, reject_alpha=False)
            raw_before = OrderedDict()
            raw_after = OrderedDict()
            for j, name in enumerate(p_names):
                if j < 3:
                    x = preproc(f['protocol{}/raw_data'.format(j + 1)][:], fs, rejection if reject else None)
                    raw_before = add_data_simple(raw_before, name, x)
                elif j > len(p_names) - 3:
                    x = preproc(f['protocol{}/raw_data'.format(j + 1)][:], fs, rejection if reject else None)
                    print(x.shape)
                    raw_after = add_data_simple(raw_after, name, x)



        xx = np.concatenate([raw_before['Opened'], raw_before['Baseline'], raw_after['Baseline'], raw_before['Left'], raw_before['Right'],  raw_after['Left'], raw_after['Right'], ])
        #xx[:, channels.index('C3')] = xx[:, channels.index('C3')]
        rejection, spatial, topography, unmixing_matrix, bandpass, _ = ICADialog.get_rejection(xx, channels, fs, mode='csp', states=None)
        from mne.viz import plot_topomap
        print(spatial)
        fig, axes = plt.subplots(ncols=rejection.topographies.shape[1])
        if not isinstance(axes, type(axes1)) :
            axes = [axes]
        for ax, top in zip(axes, rejection.topographies.T):
            plot_topomap(top, ch_names_to_2d_pos(channels), axes=ax, show=False)
        fig.savefig('csp_S{}_D{}.png'.format(subj, day+1))
        fig.show()



Example #30
0
subj = subjects[4]
subj = 'KM'


k = 1
day = 2

# load filters
filters = np.load(r'treatment\{0}d{1}_filters.npy'.format(subj, day))
topos = np.load(r'treatment\{0}d{1}_topographies.npy'.format(subj, day))
ind = np.load(r'treatment\{0}d{1}_smr_ind.npy'.format(subj, day))
ch = [c for c in channels if c != 'Pz']
left = filters[:,ind[np.argmax(np.abs(topos[ch.index('C4'), ind]))]]
right = filters[:,ind[np.argmax(np.abs(topos[ch.index('C3'), ind]))]]
from mne.viz import plot_topomap
plot_topomap(left, Montage(ch).get_pos())
plot_topomap(right, Montage(ch).get_pos())

baseline = loadmat(r'{0}\treatment\{1}\day{3}\baseline\baseline{2}.mat'.format(data_dir, subj, 1, day))['X1Topo'].T
baseline = baseline[~get_outliers_mask(baseline, iter_numb=20, std=3)]

data = [baseline]
sessions = [[0]*len(data[-1])]
for k in range(15):
    mat = loadmat(r'{0}\treatment\{1}\day{3}\proba{2}.mat'.format(data_dir, subj, k+1, day))['X1Topo'].T
    clear = mat[~get_outliers_mask(mat, iter_numb=20, std=3)]
    data.append(clear)
    sessions.append([k+1]*len(data[-1]))
df = pd.DataFrame(columns=channels, data=np.concatenate(data))
df['session'] = np.concatenate(sessions)
Example #31
0
day = 1
for day in [1, 2]:
    mat = loadmat(r'C:\Users\Nikolai\Desktop\Liza_diplom_data\Liza_diplom_data\treatment\{0}\bci\{0}_{1}1.mat'.format(subj, day))
    channels = [ch[0] for ch in mat['chan_names'][0]]
    montage = Montage(channels)
    df = pd.DataFrame(data=mat['data_cur'].T, columns=channels)


    df['state'] = mat['states_cur'][0]
    print(df['state'].unique())

    df = df.loc[~get_outliers_mask(df[channels], iter_numb=10, std=3)]

    plt.plot(df[channels])
    plt.show()


    a = QtGui.QApplication([])
    #ica = ICADialog(np.concatenate([df.loc[df['state']==6, channels], df.loc[df['state']==1, channels]]), channels, fs, mode='csp')
    ica = ICADialog(df[channels], channels, fs, mode='ica')
    ica.exec_()
    print(ica.table.get_checked_rows())


    ind = ica.table.get_checked_rows()
    for k in ind:
        plot_topomap(ica.topographies[:, k], montage.get_pos())

    np.save(r'treatment\{0}d{1}_filters.npy'.format(subj, day), ica.unmixing_matrix)
    np.save(r'treatment\{0}d{1}_topographies.npy'.format(subj, day), ica.topographies)
    np.save(r'treatment\{0}d{1}_smr_ind.npy'.format(subj, day), ind)
Example #32
0
df['block_name'] = np.concatenate([[p]*len(d) for p, d in zip(p_names, data)])
df['block_number'] = np.concatenate([[j + 1]*len(d) for j, d in enumerate(data)])
df['alpha'] = np.dot(df[channels], spat)
df['alpha_env'] = df['alpha']*0
df['time'] = np.arange(len(df)) / fs
df['signal'] = np.concatenate(signal)



fig, axes = plt.subplots(1, 5)

eeg = fft_filter(df.loc[df['block_name'].isin(['Open', 'Close']), channels], fs, band)
topo = np.dot(np.dot(eeg.T, eeg), spat)

axes[2].set_xlabel('Spat. filt.')
plot_topomap(spat, montage.get_pos(), axes=axes[2], show=False)
axes[3].set_xlabel('Topography')
plot_topomap(topo, montage.get_pos(), axes=axes[3], show=False)

axes[0].plot(df.loc[df['block_number']==2, 'time'], fft_filter(df.loc[df['block_number']==2, 'alpha'], fs, (2, 100)))
axes[0].set_xlim(31, 32)
axes[0].set_xlabel('Time, s')
axes[0].set_ylabel('Voltage, $\mu V$')
#axes[2].plot(fft_filter(df.loc[df['block_number']==2, 'alpha'], fs, (1, 45)))

axes[1].plot(*welch(df.loc[df['block_name'].isin(['Close']), 'alpha'], fs, nperseg=fs*4))
axes[1].plot(*welch(df.loc[df['block_name'].isin(['Open']), 'alpha'], fs, nperseg=fs*4))
axes[1].legend(['Close', 'Open'])
axes[1].set_xlim(5, 15)
axes[1].set_xlabel('Freq., Hz')
axes[1].set_ylabel('PSD, $\mu V^2/Hz$')
Example #33
0
def plot_results(pilot_dir, subj, channel, alpha_band=(9, 14), theta_band=(3, 6), drop_channels=None, dc=False,
                 reject_alpha=True, normalize_by='opened'):
    drop_channels = drop_channels or []
    cm = get_colors()
    fg = plt.figure(figsize=(30, 6))
    for j_s, experiment in enumerate(subj):
        with h5py.File('{}\\{}\\{}'.format(pilot_dir, experiment, 'experiment_data.h5')) as f:
            rejections, top_alpha, top_ica = load_rejections(f, reject_alpha=reject_alpha)
            fs, channels, p_names = get_info(f, drop_channels)
            ch = channels.index(channel)
            #plt.plot(fft_filter(f['protocol6/raw_data'][:, ch], fs, band=(3, 35)))
            #plt.plot(fft_filter(np.dot(f['protocol6/raw_data'], rejections)[:, ch], fs, band=(3, 35)))
            #plt.show()
            #from scipy.signal import welch
            #plt.plot(*welch(f['protocol1/raw_data'][:60*500//2, channels.index('C3')], fs, nperseg=1000))
            #plt.plot(*welch(f['protocol1/raw_data'][60*500//2:, channels.index('C3')], fs, nperseg=1000))

            #plt.plot(*welch(f['protocol2/raw_data'][:30*500//2, channels.index('C3')], fs, nperseg=1000))
            #plt.plot(*welch(f['protocol2/raw_data'][30*500//2:, channels.index('C3')], fs, nperseg=1000))
            #plt.legend(['Close', 'Open', 'Left', 'Right'])
            #plt.show()

            # collect powers
            powers = OrderedDict()
            raw = OrderedDict()
            alpha = OrderedDict()
            pow_theta = []
            for j, name in enumerate(p_names):
                pow, alpha_x, x = get_protocol_power(f, j, fs, rejections, ch, alpha_band, dc=dc)
                if 'FB' in name:
                    pow_theta.append(get_protocol_power(f, j, fs, rejections, ch, theta_band, dc=dc)[0].mean())
                powers = add_data(powers, name, pow, j)
                raw = add_data(raw, name, x, j)
                alpha = add_data(alpha, name, alpha_x, j)

            # plot rejections
            n_tops = top_ica.shape[1] + top_alpha.shape[1]
            for j_t in range(top_ica.shape[1]):
                ax = fg.add_subplot(4, n_tops * len(subj), n_tops * len(subj) * 3 + n_tops * j_s + j_t + 1)
                ax.set_xlabel('ICA{}'.format(j_t + 1))
                labels, fs = get_lsl_info_from_xml(f['stream_info.xml'][0])
                channels = [label for label in labels if label not in drop_channels]
                pos = ch_names_to_2d_pos(channels)
                plot_topomap(data=top_ica[:, j_t], pos=pos, axes=ax, show=False)
            for j_t in range(top_alpha.shape[1]):
                ax = fg.add_subplot(4, n_tops * len(subj),
                                    n_tops * len(subj) * 3 + n_tops * j_s + j_t + 1 + top_ica.shape[1])
                ax.set_xlabel('CSP{}'.format(j_t + 1))
                labels, fs = get_lsl_info_from_xml(f['stream_info.xml'][0])
                channels = [label for label in labels if label not in drop_channels]
                pos = ch_names_to_2d_pos(channels)
                plot_topomap(data=top_alpha[:, j_t], pos=pos, axes=ax, show=False)

            # plot powers
            if normalize_by == 'opened':
                norm = powers['1. Opened'].mean()
            elif normalize_by == 'beta':
                norm = np.mean(pow_theta)
            else:
                print('WARNING: norm = 1')
            print('norm', norm)

            ax1 = fg.add_subplot(3, len(subj), j_s + 1)
            ax = fg.add_subplot(3, len(subj), j_s + len(subj) + 1)
            t = 0
            for j_p, ((name, pow), (name, x)) in enumerate(zip(powers.items(), raw.items())):
                if name == '2228. FB':
                    from scipy.signal import periodogram
                    fff = plt.figure()
                    fff.gca().plot(*periodogram(x, fs, nfft=fs * 3), c=cm[name.split()[1]])
                    plt.xlim(0, 80)
                    plt.ylim(0, 3e-11)
                    plt.show()
                print(name)
                time = np.arange(t, t + len(x)) / fs
                color = cm[''.join([i for i in name.split()[1] if not i.isdigit()])]
                ax1.plot(time, fft_filter(x, fs, (2, 45)), c=color, alpha=0.4)
                ax1.plot(time, alpha[name], c=color)
                t += len(x)
                ax.plot([j_p], [pow.mean() / norm], 'o', c=color, markersize=10)
                ax.errorbar([j_p], [pow.mean() / norm], yerr=pow.std() / norm, c=color, ecolor=color)
            fb_x = np.hstack([[j] * len(pows) for j, (key, pows) in enumerate(powers.items()) if 'FB' in key])
            fb_y = np.hstack([pows for key, pows in powers.items() if 'FB' in key]) / norm
            sns.regplot(x=fb_x, y=fb_y, ax=ax, color=cm['FB'], scatter=False, truncate=True)

            ax1.set_xlim(0, t / fs)
            ax1.set_ylim(-40, 40)
            plt.setp(ax.xaxis.get_majorticklabels(), rotation=70)
            ax.set_xticks(range(len(powers)))
            ax.set_xticklabels(powers.keys())
            ax.set_ylim(0, 3)
            ax.set_xlim(-1, len(powers))
            ax1.set_title('Day {}'.format(j_s + 1))
    return fg
Example #34
0
channels = [ch[0] for ch in mat['chan_names'][0]]
montage = Montage(channels)
df = pd.DataFrame(data=mat['data_cur'].T, columns=channels)

print(channels)
print(1000*np.isin(np.array(channels), ['Fp1', 'Fp2', 'F7', 'F8', 'Ft9', 'Ft10', 'T7', 'T8', 'Tp9', 'Tp10']))

df['state'] = mat['states_cur'][0]
print(df['state'].unique())

df = df.loc[~get_outliers_mask(df[channels], iter_numb=10, std=3)]

plt.plot(df[channels])
plt.show()

ica = CSPDecomposition(channels, fs, band)
df = df.loc[df.state.isin([6, 1])]
scores, filters, topos = ica.decompose(df[channels].as_matrix(), df['state']-1)
for k in range(len(topos)):
    plot_topomap(topos[:, k], montage.get_pos())
sources = fft_filter(np.dot(df[channels], filters), fs, band)
desyncs = sources[df.state == 6].std(0)/sources[df.state == 1].std(0)
smr_ind = np.argmax(desyncs)
df['SMR'+str(1)] = np.dot(df[channels], filters[:, smr_ind])
plot_topomap(filters[:, smr_ind], montage.get_pos())
plot_topomap(topos[:, smr_ind], montage.get_pos())
#df['SMR-env'+str(state)] = np.abs(hilbert(fft_filter(df[state+'SMR'], fs, [9, 13])))
plt.plot(df['SMR'+str(1)])
plt.plot(df['C3'])
plt.plot(df['C4'])
plt.show()
    data = y_df.query('metric_type == "{}"'.format(metric_type))
    md = sm.MixedLM.from_formula("np.log(env) ~ k:fb_type:channel",
                                 data,
                                 groups=data["subj_id"],
                                 re_formula='1+k:channel:fb_type')

    results = md.fit()

    print(results.summary())

#topo0 = np.exp([results.params['channel[T.{}]'.format(ch)] if ch !='C3' else 0 for ch in CHANNELS])
topo_fb0 = np.exp([
    results.params['k:fb_type[FBMock]:channel[{}]'.format(ch)]
    for ch in CHANNELS
])
plot_topomap(topo_fb0, MONTAGE.get_pos(), vmin=0, vmax=1)

md = sm.MixedLM.from_formula("np.log(env) ~ channel + k:fb_type:channel",
                             data,
                             groups=data["subj_id"],
                             re_formula='1')
results = md.fit()
print(results.summary())

m = sm.OLS.from_formula(
    'env ~ fb_type*channel',
    data=y_df.query('metric_type == "n_spindles" & k==0')).fit()
#m1 = sm.OLS.from_formula('env ~ fb_type:k', data=y_df.query('metric_type == "n_spindles" & channel=="P4"')).fit()
print(m.summary())
from statsmodels.stats.anova import anova_lm
anova_lm(m)
X = epochs.get_data()
y = label_binarize(epochs.events[:, 2], classes=[1, 3]).ravel()

clf = make_pipeline(XdawnTransformer(n_components=2),
                    Vectorizer(),
                    StandardScaler(),
                    LogisticRegression())

# Define a monte-carlo cross-validation generator (reduce variance):
cv = ShuffleSplit(len(y), 10, test_size=0.2, random_state=42)

scores = cross_val_score(clf, X, y, cv=cv)

class_balance = np.mean(y == y[0])
class_balance = max(class_balance, 1. - class_balance)
print("Classification accuracy: %f / Chance level: %f" % (np.mean(scores),
                                                          class_balance))

###############################################################################
# plot Xdawn patterns estimated on full data for visualization

xdawn = XdawnTransformer(n_components=2)
xdawn.fit(X, y)
data = xdawn.patterns_
fig, axes = plt.subplots(1, 4)
for idx in range(4):
    plot_topomap(data[idx], epochs.info, axes=axes[idx], show=False)
fig.suptitle('Xdawn patterns')
fig.tight_layout()
plt.show()
    # get signals at significant sensors
    signals = data[..., ch_inds].mean(axis=-1)
    sig_times = times[time_inds]

    # create spatial mask
    mask = np.zeros((T_obs_map.shape[0], 1), dtype=bool)
    mask[ch_inds, :] = True

    # initialize figure
    fig, ax_topo = plt.subplots(1, 1, figsize=(10, 3))
    title = 'Cluster #{0}'.format(i_clu + 1)
    fig.suptitle(title, fontsize=14)

    # plot average test statistic and mark significant sensors
    image, _ = plot_topomap(T_obs_map, pos, mask=mask, axes=ax_topo,
                            vmin=T_obs_min, vmax=T_obs_max,
                            show=False)

    # advanced matplotlib for showing image with figure and colorbar
    # in one plot
    divider = make_axes_locatable(ax_topo)

    # add axes for colorbar
    ax_colorbar = divider.append_axes('right', size='5%', pad=0.05)
    plt.colorbar(image, cax=ax_colorbar)
    ax_topo.set_xlabel('Averaged T-map ({:0.1f} - {:0.1f} ms)'.format(
        *sig_times[[0, -1]]
    ))

    # add new axis for time courses and plot time courses
    ax_signals = divider.append_axes('right', size='300%', pad=1.2)
Example #38
0
def plot_results(fourier_ica_obj, meg_data,
                 W_orig, A_orig, info, picks,
                 cluster_quality=[], fnout=None,
                 show=True, plot_all=True):

    """
    Generate plot containing all results achieved by
    applying FourierICA, i.e., plot activations in
    time- and source-space, as well as fourier
    amplitudes and topoplots.

        Parameters
        ----------
        fourier_ica_obj: FourierICA object
        meg_data: array of data to be decomposed [nchan, ntsl].
        W_orig: estimated de-mixing matrix
        A_orig: estimated mixing matrix
        info: instance of mne.io.meas_info.Info
            Measurement info.
        picks: Channel indices to generate topomap coords for.
        cluster_quality: if set cluster quality is added as text
            info on the plot. Cluster quality is of interest when
            FourierICA combined with ICASSO was applied.
            default: cluster_quality=[]
        fnout: output name for the result image. If not set, the
            image won't be saved. Note, the ending '.png' is
            automatically added
            default: fnout=None
        show: if set plotting results are shown
            default: show=True
        plot_all: if set results for all components are plotted.
            Otherwise only the first 10 components are plotted.
            default: plot_all=True
    """



    # ------------------------------------------
    # import necessary modules
    # ------------------------------------------
    from matplotlib import pyplot as plt
    from matplotlib import gridspec as grd
    from mne.viz import plot_topomap
    from mne.channels.layout import _find_topomap_coords
    import types

    # ------------------------------------------
    # generate sources for plotting
    # ------------------------------------------
    temporal_envelope, pk_values = fourier_ica_obj.get_temporal_envelope(meg_data, W_orig)
    rec_signal_avg, orig_avg = fourier_ica_obj.get_reconstructed_signal(meg_data, W_orig, A_orig)
    fourier_ampl = fourier_ica_obj.get_fourier_ampl(meg_data, W_orig)


    # ------------------------------------------
    # collect some general information
    # ------------------------------------------
    ntsl = int(np.floor(fourier_ica_obj.sfreq*fourier_ica_obj.win_length_sec))
    tpost = fourier_ica_obj.tpre + fourier_ica_obj.win_length_sec
    nchan, ncomp = A_orig.shape
    nbins = fourier_ampl.shape[1]
    sfreq_bins = nbins/(fourier_ica_obj.fhigh - fourier_ica_obj.flow)

    # define axis/positions for plots
    xaxis_time = np.arange(ntsl)/fourier_ica_obj.sfreq + fourier_ica_obj.tpre
    xaxis_fourier = np.arange(nbins)/sfreq_bins + fourier_ica_obj.flow
    ylim_act = [np.min(temporal_envelope), np.max(temporal_envelope)]
    ylim_meg = [np.min(orig_avg), np.max(orig_avg)]
    pos = _find_topomap_coords(info, picks)

    # ------------------------------------------
    # loop over all activations
    # ------------------------------------------
    plt.ioff()
    if plot_all:
        nimg = int(np.ceil(ncomp /10.0))
    else:
        nimg = 1

    if isinstance(A_orig[0, 0], types.ComplexType):
        nplots_per_comp = 8
    else:
        nplots_per_comp = 7


    # loop over all images
    for iimg in range(nimg):

        fig = plt.figure('FourierICA plots', figsize=(18, 14))

        # estimate how many plots on current image
        istart_plot = int(10*iimg)
        nplot = np.min([10*(iimg+1), ncomp])
        gs = grd.GridSpec(10, nplots_per_comp)

        for icomp in range(istart_plot, nplot):

            if icomp == nplot-1:
                spines = ['bottom']
            else:
                spines = []

            # ----------------------------------------------
            # (1.) plot activations in time domain
            # ----------------------------------------------
            p1 = plt.subplot(gs[icomp-istart_plot, 0:2])
            plt.xlim(fourier_ica_obj.tpre, tpost)
            plt.ylim(ylim_act)
            adjust_spines(p1, spines, labelsize=13)
            if icomp == nplot-1:
                plt.xlabel('time [s]')
            elif icomp == istart_plot:
                p1.set_title("activations [time domain]")
            p1.plot(xaxis_time, temporal_envelope[icomp, :])

            # add some information
            txt_info = 'cluster qual.: %0.2f; ' % cluster_quality[icomp] if cluster_quality.any() else ''

            if pk_values.any():
                txt_info += 'pk: %0.2f' % pk_values[icomp]
                p1.text(0.97*fourier_ica_obj.tpre+0.03*tpost, 0.8*ylim_act[1] + 0.1*ylim_act[0],
                        txt_info, color='r')


            IC_number = 'IC#%d' % (icomp+1)
            p1.text(1.1*fourier_ica_obj.tpre-0.1*tpost, 0.4*ylim_act[1] + 0.6*ylim_act[0],
                    IC_number, color='black', rotation=90)

            # ----------------------------------------------
            # (2.) plot back-transformed signals
            # ----------------------------------------------
            p2 = plt.subplot(gs[icomp-istart_plot, 2:4])
            plt.xlim(fourier_ica_obj.tpre, tpost)
            plt.ylim(ylim_meg)
            adjust_spines(p2, spines, labelsize=13)
            if icomp == nplot-1:
                plt.xlabel('time [s]')
            elif icomp == istart_plot:
                p2.set_title("reconstructed MEG-signals")
            p2.plot(xaxis_time, orig_avg.T, 'b', linewidth=0.5)
            p2.plot(xaxis_time, rec_signal_avg[icomp, :, :].T, 'r', linewidth=0.5)

            # ----------------------------------------------
            # (3.) plot Fourier amplitudes
            # ----------------------------------------------
            p3 = plt.subplot(gs[icomp-istart_plot, 4:6])
            plt.xlim(fourier_ica_obj.flow, fourier_ica_obj.fhigh)
            plt.ylim(0.0, 1.0)
            adjust_spines(p3, spines, labelsize=13)
            if icomp == nplot-1:
                plt.xlabel('freq [Hz]')
            elif icomp == istart_plot:
                p3.set_title("Fourier amplitude (arbitrary units)")

            p3.bar(xaxis_fourier, fourier_ampl[icomp, :], 0.8, color='b')

            # ----------------------------------------------
            # (4.) topoplots (magnitude / phase difference)
            # ----------------------------------------------
            if isinstance(A_orig[0, icomp], types.ComplexType):
                magnitude = np.abs(A_orig[:, icomp])
                magnitude = (2 * magnitude/np.max(magnitude)) - 1
                p4 = plt.subplot(gs[icomp-istart_plot, 6])
                im, _ = plot_topomap(magnitude, pos, res=200, vmin=-1, vmax=1, contours=0)
                if icomp == istart_plot:
                    p4.set_title("Magnitude")
                if icomp == nplot-1:
                    cbar = plt.colorbar(im, ticks=[-1, 0, 1], orientation='horizontal', shrink=0.8,
                                        fraction=0.04, pad=0.04)
                    cbar.ax.set_yticklabels(['-1.0', '0.0', '1.0'])

                phase_diff = (np.angle(A_orig[:, icomp]) + np.pi) / (2 * np.pi)
                p5 = plt.subplot(gs[icomp-istart_plot, 7])
                im, _ = plot_topomap(phase_diff, pos, res=200, vmin=0, vmax=1, contours=0)
                if icomp == istart_plot:
                    p5.set_title("Phase differences")
                if icomp == nplot-1:
                    cbar = plt.colorbar(im, ticks=[-1, 0, 1], orientation='horizontal', shrink=0.9,
                                        fraction=0.04, pad=0.04)
                    cbar.ax.set_yticklabels(['0.0', '0.5', '1.0'])

            else:
                from jumeg.jumeg_math import rescale
                p4 = plt.subplot(gs[icomp-istart_plot, 6])
                magnitude = A_orig[:, icomp]
                magnitude = rescale(magnitude, -1, 1)
                im, _ = plot_topomap(magnitude, pos, res=200, vmin=-1, vmax=1, contours=0)
                if icomp == istart_plot:
                    p4.set_title("Magnitude distribution")
                if icomp == nplot-1:
                    cbar = plt.colorbar(im, ticks=[-1, 0, 1], orientation='horizontal', shrink=0.9,
                                        fraction=0.04, pad=0.04)
                    cbar.ax.set_yticklabels(['-1.0', '0.0', '1.0'])

        # save image
        if fnout:
            if plot_all:
                fnout_complete = '%s%2d.png' % (fnout, iimg+1)
            else:
                fnout_complete = '%s.png' % fnout

            plt.savefig(fnout_complete, format='png')

        # show image if requested
        if show:
            plt.show()

        plt.close('FourierICA plots')

    plt.ion()

    return pk_values
Example #39
0
def ICs_topoplot(A_orig, info, picks, fnout=None, show=True):

    """
    Generate topoplots from the demixing matrix recieved
    by applying FourierICA.

        Parameters
        ----------
        fourier_ica_obj: FourierICA object
        info: instance of mne.io.meas_info.Info
            Measurement info.
        picks: Channel indices to generate topomap coords for.
        fnout: output name for the result image. If not set, the
            image won't be saved. Note, the ending '.png' is
            automatically added
            default: fnout=None
        show: if set plotting results are shown
            default: show=True
    """

    # ------------------------------------------
    # import necessary modules
    # ------------------------------------------
    from matplotlib import pyplot as plt
    from matplotlib import gridspec as grd
    from mne.viz import plot_topomap
    from mne.channels.layout import _find_topomap_coords
    import types

    # ------------------------------------------
    # collect some general information
    # ------------------------------------------
    nchan, ncomp = A_orig.shape

    # define axis/positions for plots
    pos = _find_topomap_coords(info, picks)

    plt.ioff()
    plt.figure('Topoplots', figsize=(5, 14))
    nplot = np.min([10, ncomp])

    if isinstance(A_orig[0, 0], types.ComplexType):
        nplots_per_comp = 2
    else:
        nplots_per_comp = 1

    gs = grd.GridSpec(nplot, nplots_per_comp)

    # ------------------------------------------
    # loop over all activations
    # ------------------------------------------
    for icomp in range(nplot):

        # ----------------------------------------------
        # (topoplots (magnitude / phase difference)
        # ----------------------------------------------
        if isinstance(A_orig[0, icomp], types.ComplexType):
            magnitude = np.abs(A_orig[:, icomp])
            magnitude = (2 * magnitude/np.max(magnitude)) - 1
            p1 = plt.subplot(gs[icomp, 0])
            im, _ = plot_topomap(magnitude, pos, res=200, vmin=-1, vmax=1, contours=0)
            if icomp == 0:
                p1.set_title("Magnitude")
            if icomp == nplot-1:
                cbar = plt.colorbar(im, ticks=[-1, 0, 1], orientation='horizontal', shrink=0.8)
                cbar.ax.set_yticklabels(['-1.0', '0.0', '1.0'])

            phase_diff = (np.angle(A_orig[:, icomp]) + np.pi) / (2 * np.pi)
            p2 = plt.subplot(gs[icomp, 1])
            im, _ = plot_topomap(phase_diff, pos, res=200, vmin=0, vmax=1, contours=0)
            if icomp == 0:
                p2.set_title("Phase differences")
            if icomp == nplot-1:
                cbar = plt.colorbar(im, ticks=[-1, 0, 1], orientation='horizontal', shrink=0.8)
                cbar.ax.set_yticklabels(['0.0', '0.5', '1.0'])

        else:
            p1 = plt.subplot(gs[icomp, 0:2])
            magnitude = A_orig[:, icomp]
            magnitude = (2 * magnitude/np.max(magnitude)) - 1
            plot_topomap(magnitude, pos, res=200, vmin=-1, vmax=1, contours=0)
            if icomp == 0:
                p1.set_title("Magnitude distribution")
            if icomp == nplot-1:
                cbar = plt.colorbar(im, ticks=[-1, 0, 1], orientation='horizontal', shrink=0.8)
                cbar.ax.set_yticklabels(['-1.0', '0.0', '1.0'])

    # save image
    if fnout:
        plt.savefig(fnout + '.png', format='png')

    # show image if requested
    if show:
        plt.show()

    plt.close('Topoplots')
    plt.ion()
    # get topography for F stat
    f_map = T_obs[time_inds, ...].mean(axis=0)

    # get signals at the sensors contributing to the cluster
    sig_times = epochs.times[time_inds]

    # create spatial mask
    mask = np.zeros((f_map.shape[0], 1), dtype=bool)
    mask[ch_inds, :] = True

    # initialize figure
    fig, ax_topo = plt.subplots(1, 1, figsize=(10, 3))

    # plot average test statistic and mark significant sensors
    image, _ = plot_topomap(f_map, pos, mask=mask, axes=ax_topo, cmap='Reds',
                            vmin=np.min, vmax=np.max, show=False)

    # create additional axes (for ERF and colorbar)
    divider = make_axes_locatable(ax_topo)

    # add axes for colorbar
    ax_colorbar = divider.append_axes('right', size='5%', pad=0.05)
    plt.colorbar(image, cax=ax_colorbar)
    ax_topo.set_xlabel(
        'Averaged F-map ({:0.3f} - {:0.3f} s)'.format(*sig_times[[0, -1]]))

    # add new axis for time courses and plot time courses
    ax_signals = divider.append_axes('right', size='300%', pad=1.2)
    title = 'Cluster #{0}, {1} sensor'.format(i_clu + 1, len(ch_inds))
    if len(ch_inds) > 1:
        title += "s (mean)"
Example #41
0
    a = QApplication([])
    ica = ICADialog(x, channels, fs, mode=mode)
    ica.exec_()
    a.exit()
    return ica.spatial, ica.topography

def runica2(x, fs, channels, names=('Right', 'Left'), mode='ica'):
    from PyQt5.QtWidgets import QApplication
    from pynfb.protocols.ssd.topomap_selector_ica import ICADialog
    a = QApplication([])
    res = []
    decomposition = None
    for n in names:
        print('*** Select component for condition: ' + n)
        ica = ICADialog(x, channels, fs, decomposition=decomposition, mode=mode)
        ica.exec_()
        res.append(np.array((ica.spatial, ica.topography)))
        decomposition = ica.decomposition
    a.exit()
    return res


if __name__ == '__main__':
    from mne.viz import plot_topomap
    from pynfb.inlets.montage import Montage
    from pynfb.generators import ch_names32
    montage = Montage(ch_names32)
    spatial, topo = runica(np.random.normal(size=(100000, 32)), 1000, montage.get_names(), mode='csp')
    plot_topomap(spatial, montage.get_pos())
    plot_topomap(topo, montage.get_pos())
    # get signals at significant sensors
    signals = grand_ave[..., ch_inds].mean(axis=-1)
    sig_times = times[time_inds]

    # create spatial mask
    mask = np.zeros((f_map.shape[0], 1), dtype=bool)
    mask[ch_inds, :] = True

    # initialize figure
    fig, ax_topo = plt.subplots(1, 1, figsize=(10, 3))
    title = "Cluster #{0}".format(i_clu + 1)
    fig.suptitle(title, fontsize=14)

    # plot average test statistic and mark significant sensors
    image, _ = plot_topomap(f_map, pos, mask=mask, axes=ax_topo, cmap="Reds", vmin=np.min, vmax=np.max)

    # advanced matplotlib for showing image with figure and colorbar
    # in one plot
    divider = make_axes_locatable(ax_topo)

    # add axes for colorbar
    ax_colorbar = divider.append_axes("right", size="5%", pad=0.05)
    plt.colorbar(image, cax=ax_colorbar)
    ax_topo.set_xlabel("Averaged F-map ({:0.1f} - {:0.1f} ms)".format(*sig_times[[0, -1]]))

    # add new axis for time courses and plot time courses
    ax_signals = divider.append_axes("right", size="300%", pad=1.2)
    for signal, name, col, ls in zip(signals, condition_names, colors, linestyles):
        ax_signals.plot(times, signal, color=col, linestyle=ls, label=name)
    # get signals at significant sensors
    signals = grand_ave[..., ch_inds].mean(axis=-1)
    sig_times = times[time_inds]

    # create spatial mask
    mask = np.zeros((f_map.shape[0], 1), dtype=bool)
    mask[ch_inds, :] = True

    # initialize figure
    fig, ax_topo = plt.subplots(1, 1, figsize=(10, 3))
    title = 'Cluster #{0}'.format(i_clu + 1)
    fig.suptitle(title, fontsize=14)

    # plot average test statistic and mark significant sensors
    image, _ = plot_topomap(f_map, pos, mask=mask, axis=ax_topo,
                            cmap='Reds', vmin=np.min, vmax=np.max)

    # advanced matplotlib for showing image with figure and colorbar
    # in one plot
    divider = make_axes_locatable(ax_topo)

    # add axes for colorbar
    ax_colorbar = divider.append_axes('right', size='5%', pad=0.05)
    plt.colorbar(image, cax=ax_colorbar)
    ax_topo.set_xlabel('Averaged F-map ({:0.1f} - {:0.1f} ms)'.format(
        *sig_times[[0, -1]]
    ))

    # add new axis for time courses and plot time courses
    ax_signals = divider.append_axes('right', size='300%', pad=1.2)
    for signal, name, col, ls in zip(signals, condition_names, colors,
Example #44
0
 def fs_class_freq_topo_kernel(self, layer_name):
     layer_name = self._check_layer_name(layer_name)
     class_data = self._class_data(self.data)
     _input = self.model.input
     _output = self.model.output
     ib = ['2-8', '8-12', '12-20', '20-30', '30-60']
     plt.rcParams['font.size'] = 12
     for name in layer_name:
         layer = self.layer_dict[name]
         _weights = layer.get_weights()[0]
         layer_model = tf.keras.Model([_input], [layer.output, _output])
         fig = plt.figure(figsize=(8, 6))
         gs = fig.add_gridspec(2, 2)
         for c in class_data:
             axs = fig.add_subplot(gs[c])
             ax = inset_axes(axs,
                             '100%',
                             '100%',
                             bbox_to_anchor=(0, 0.25, 1, 0.5),
                             bbox_transform=axs.transAxes,
                             borderpad=0)
             cax = inset_axes(axs,
                              '100%',
                              '100%',
                              bbox_to_anchor=(0.65, 0.65, 0.09, 0.03),
                              bbox_transform=axs.transAxes,
                              borderpad=0)
             text_0 = inset_axes(axs,
                                 '100%',
                                 '100%',
                                 bbox_to_anchor=(0.62, 0.65, 0.03, 0.03),
                                 bbox_transform=axs.transAxes,
                                 borderpad=0)
             text_1 = inset_axes(axs,
                                 '100%',
                                 '100%',
                                 bbox_to_anchor=(0.74, 0.65, 0.03, 0.03),
                                 bbox_transform=axs.transAxes,
                                 borderpad=0)
             cax_text = inset_axes(axs,
                                   '100%',
                                   '100%',
                                   bbox_to_anchor=(0.77, 0.65, 0.23, 0.03),
                                   bbox_transform=axs.transAxes,
                                   borderpad=0)
             title = inset_axes(axs,
                                '100%',
                                '100%',
                                bbox_to_anchor=(0, 0.65, 0.62, 0.03),
                                bbox_transform=axs.transAxes,
                                borderpad=0)
             self._ban_axis(axs)
             self._ban_axis(ax)
             self._ban_axis(cax)
             self._ban_axis(cax_text)
             self._ban_axis(text_0)
             self._ban_axis(text_1)
             self._ban_axis(title)
             ax.set_xlabel('({}) {}'.format(chr(c + 97),
                                            self.class_names[c]))
             ibclass_data = interestingband(class_data[c]['x'],
                                            ib,
                                            axis=-2,
                                            swapaxes=False)
             cax_text.text(0.5,
                           0.5,
                           'contribution',
                           horizontalalignment='center',
                           verticalalignment='center',
                           transform=cax_text.transAxes)
             text_0.text(0,
                         0.5,
                         '0',
                         horizontalalignment='left',
                         verticalalignment='center',
                         transform=text_0.transAxes)
             text_1.text(1,
                         0.5,
                         '1',
                         horizontalalignment='right',
                         verticalalignment='center',
                         transform=text_1.transAxes)
             title.text(0.02,
                        0.5,
                        'Inter-band topomap of class',
                        horizontalalignment='left',
                        verticalalignment='center',
                        transform=title.transAxes)
             s_weights = []
             for i in np.arange(ibclass_data.shape[0]):
                 with tf.GradientTape() as g:
                     conv_output, Pred = layer_model(ibclass_data[i])
                     prob = Pred[:, c]
                     grads = g.gradient(prob, conv_output)
                 pooled_grads = K.sum(grads, axis=(0, 1, 2))
                 pooled_grads = tf.reshape(pooled_grads,
                                           shape=(_weights.shape[-2],
                                                  _weights.shape[-1]))
                 s_weights.append(
                     np.mean(np.abs(np.array(pooled_grads * _weights)),
                             axis=(1, 2, 3)))
             s_weights = normalization(np.array(s_weights), axis=None)
             s_weights = [
                 s_weights[i, :] for i in range(s_weights.shape[0])
             ]
             for i in np.arange(len(s_weights)):
                 width = 1. / len(s_weights)
                 ax_i = inset_axes(ax,
                                   '100%',
                                   '100%',
                                   bbox_to_anchor=(0 + width * i, 0, width,
                                                   1),
                                   bbox_transform=ax.transAxes,
                                   borderpad=0)
                 ax_i.set_xlabel('{}'.format(ib[i] + 'Hz'))
                 # self._ban_axis(ax_i)
                 im, cn = viz.plot_topomap(
                     s_weights[i],
                     self.locs,
                     names=self.sensors_name,
                     show_names=True,
                     show=False,
                     image_interp='bicubic',
                     cmap='RdBu_r',
                     extrapolate='head',
                     sphere=(0, 0, 0, 1))  # draw topographic image
             cbar = plt.colorbar(im, cax=cax, orientation='horizontal')
             cbar.set_ticks([])
         plt.tight_layout(pad=0.25, h_pad=0, w_pad=1)
         fig.savefig(os.path.join('fs_class_freq_topo_kernel.png'),
                     format='png',
                     transparent=False,
                     dpi=300,
                     pad_inches=0)
         plt.show(block=False)
Example #45
0
n_exp = 24
print(n_exp)


exp = experiments.iloc[n_exp]
desc = '{}-{}-{}-{}'.format(exp['subject'], exp['protocol'], {0: 'exp', 1:'control'}[exp['control']], '-'.join(exp.dataset.split('_')[-2:]))
print(exp, '\n*******************', desc, '\n*******************')
df, fs, p_names, channels = load_data('{}{}/experiment_data.h5'.format(data_dir, exp.dataset))
channels = channels[:32]
df = df[~get_outliers_mask(df[channels], std=3)]

right, left = runica2(df.loc[df['block_number'].isin([1, 2, 3, 7, 8, 9]), channels], fs, channels, ['RIGHT', 'LEFT'])
np.save(wdir + desc + '-RIGHT.npy', right)
np.save(wdir + desc + '-LEFT.npy', left)


# load and plot
right = np.load(wdir + desc + '-RIGHT.npy')
left = np.load(wdir + desc + '-LEFT.npy')
f, ax = plt.subplots(1, 4)
plot_topomap(right[0], Montage(channels).get_pos(), contours=0, axes=ax[0], show=False)
plot_topomap(right[1], Montage(channels).get_pos(), contours=0, axes=ax[1], show=False)
plot_topomap(left[0], Montage(channels).get_pos(), contours=0, axes=ax[2], show=False)
plot_topomap(left[1], Montage(channels).get_pos(), contours=0, axes=ax[3], show=False)
ax[0].set_title('Right spat.')
ax[1].set_title('Right topog.')
ax[2].set_title('Left spat.')
ax[3].set_title('Left topog.')
ax[0].set_ylabel(desc)
plt.savefig(wdir + desc+'-SMR-filters.png')
plt.show()
Example #46
0
        tidx = np.arange(np.argmin(np.abs(times - time[0])),
                         np.argmin(np.abs(times - time[1])))
        plt_dat = np.average(dcond[:, :, :, tidx], 3)
        plt_dat = np.average(plt_dat[:, :, fidx], 2)

        p_dat = pvals
        p_dat = np.average(p_dat[:, :, tidx], 2)
        p_dat = np.average(p_dat[:, fidx], 1)

        mask = np.where(p_dat < param['alpha'], 1, 0)

        plot_topomap(np.average(plt_dat, 0),
                     pltdat.info,
                     show=False,
                     cmap='viridis',
                     vmin=-0.2,
                     vmax=0.2,
                     mask=mask,
                     axes=axes[idx],
                     contours=False)

        axes[idx].set_title(c, fontdict={'fontsize': param['titlefontsize']})
    # Get data of interest

    # Second line Significance at Fz, Cz, Pz
    # Same with topo between sig freqs
    # Bar plot 20-40 Hz; 500-600 ms
    # Topo plot 20-40 Hz 500-600 ms
    plt.tight_layout()

    cax = fig2.add_axes([0.28, 0.40, 0.08, 0.05], label="cbar1")
Example #47
0
                        powers['{}. Opened'.format(j+1)] = pow[len(pow)//2:]
                    elif name == 'Rotate':
                        powers['{}. Right'.format(j+1)] = pow[:len(pow)//2]
                        powers['{}. Left'.format(j+1)] = pow[len(pow)//2:]
                    else:
                        powers['{}. {}'.format(j+1, name)] = pow


                # plot rejections
                for j_t in range(top_ica.shape[1]):
                    ax = fg.add_subplot(5, top_ica.shape[1]*len(subj), top_ica.shape[1]*len(subj)*3 + top_ica.shape[1]*j_s + j_t + 1)
                    ax.set_xlabel('ICA{}'.format(j_t+1))
                    labels, fs = get_lsl_info_from_xml(f['stream_info.xml'][0])
                    channels = [label for label in labels if label not in drop_channels]
                    pos = ch_names_to_2d_pos(channels)
                    plot_topomap(data=top_ica[:, j_t], pos=pos, axes=ax, show=False)
                for j_t in range(top_alpha.shape[1]):
                    ax = fg.add_subplot(5, top_alpha.shape[1]*len(subj), top_alpha.shape[1]*len(subj)*4 + top_alpha.shape[1]*j_s + j_t + 1)
                    ax.set_xlabel('CSP{}'.format(j_t+1))
                    labels, fs = get_lsl_info_from_xml(f['stream_info.xml'][0])
                    channels = [label for label in labels if label not in drop_channels]
                    pos = ch_names_to_2d_pos(channels)
                    plot_topomap(data=top_alpha[:, j_t], pos=pos, axes=ax, show=False)


                # plot powers
                norm = powers['{}. Baseline'.format(p_names.index('Baseline') + 1)].mean()
                #norm = np.mean(pow_theta)
                print('norm', norm)
                ax = fg.add_subplot(2, len(subj), j_s + 1)
                for j_p, (name, pow) in enumerate(powers.items()):
Example #48
0
    data_dir, exp.dataset))
df = df[~get_outliers_mask(df[channels], std=3)]

right, left = runica2(
    df.loc[df['block_number'].isin([1, 2, 3, 7, 8, 9]), channels], fs,
    channels, ['RIGHT', 'LEFT'])
np.save(wdir + desc + '-RIGHT.npy', right)
np.save(wdir + desc + '-LEFT.npy', left)

# load and plot
right = np.load(wdir + desc + '-RIGHT.npy')
left = np.load(wdir + desc + '-LEFT.npy')
f, ax = plt.subplots(1, 4)
plot_topomap(right[0],
             Montage(channels).get_pos(),
             contours=0,
             axes=ax[0],
             show=False)
plot_topomap(right[1],
             Montage(channels).get_pos(),
             contours=0,
             axes=ax[1],
             show=False)
plot_topomap(left[0],
             Montage(channels).get_pos(),
             contours=0,
             axes=ax[2],
             show=False)
plot_topomap(left[1],
             Montage(channels).get_pos(),
             contours=0,
Example #49
0
                elif len(lengths_buffer) > 0:
                    lengths.append(np.mean(lengths_buffer))
                    lengths_buffer = []
            print(lengths)
            return np.array(lengths)



        with h5py.File('{}\\{}\\{}'.format(dir_, experiment, 'experiment_data.h5')) as f:
            fs, channels, p_names = get_info(f, settings['drop_channels'])
            if reject:
                rejections = load_rejections(f, reject_alpha=True)[0]
            else:
                rejections = None
            spatial = f['protocol15/signals_stats/left/spatial_filter'][:]
            plot_topomap(spatial, ch_names_to_2d_pos(channels), axes=plt.gca(), show=False)
            plt.savefig('alphaS{}_Day{}_spatial_filter'.format(subj, day+1))
            mu_band = f['protocol15/signals_stats/left/bandpass'][:]
            #mu_band = (12, 13)
            max_gap = 1 / min(mu_band) * 2
            min_sate_duration = max_gap * 2
            raw = OrderedDict()
            signal = OrderedDict()
            for j, name in enumerate(p_names):
                x = preproc(f['protocol{}/raw_data'.format(j + 1)][:], fs, rejections)
                raw = add_data(raw, name, x, j)
                signal = add_data(signal, name, f['protocol{}/signals_data'.format(j + 1)][:], j)

        del raw[list(raw.keys())[-1]]
        # make csp:
        if run_ica:
Example #50
0
                elif j > len(p_names) - 3:
                    x = preproc(f['protocol{}/raw_data'.format(j + 1)][:], fs,
                                rejection if reject else None)
                    print(x.shape)
                    raw_after = add_data_simple(raw_after, name, x)

        xx = np.concatenate([
            raw_before['Opened'],
            raw_before['Baseline'],
            raw_after['Baseline'],
            raw_before['Left'],
            raw_before['Right'],
            raw_after['Left'],
            raw_after['Right'],
        ])
        #xx[:, channels.index('C3')] = xx[:, channels.index('C3')]
        rejection, spatial, topography, unmixing_matrix, bandpass, _ = ICADialog.get_rejection(
            xx, channels, fs, mode='csp', states=None)
        from mne.viz import plot_topomap
        print(spatial)
        fig, axes = plt.subplots(ncols=rejection.topographies.shape[1])
        if not isinstance(axes, type(axes1)):
            axes = [axes]
        for ax, top in zip(axes, rejection.topographies.T):
            plot_topomap(top,
                         ch_names_to_2d_pos(channels),
                         axes=ax,
                         show=False)
        fig.savefig('csp_S{}_D{}.png'.format(subj, day + 1))
        fig.show()
Example #51
0
        channels = [ch[0] for ch in mat['chan_names'][0]]
        montage = Montage(channels)
        df = pd.DataFrame(data=mat['data_cur'].T, columns=channels)
        df['state'] = mat['states_cur'][0]
        df = df.loc[~get_outliers_mask(df[channels], iter_numb=10, std=3)]
        df['block_name'] = df['state'].apply(lambda x: {6: 'Rest', 1: 'Left', 2: 'Right'}[x])
        filters = np.load(r'treatment\{0}d{1}_filters.npy'.format(subj, day+1))
        topos = np.load(r'treatment\{0}d{1}_topographies.npy'.format(subj, day+1))
        ind = np.load(r'treatment\{0}d{1}_smr_ind.npy'.format(subj, day+1))
        for k in range(2):
            spat = filters[:, ind[k]]
            topo = topos[:, ind[k]]
            df['smr'] = np.dot(df[channels], spat)

            axes[day + 2*s, 0 + 3*k].set_xlabel('Spat. filt.')
            plot_topomap(spat, montage.get_pos(), axes=axes[day + 2*s, 0+ 3*k], show=False, contours=0)
            axes[day + 2*s, 1+ 3*k].set_xlabel('Topography')
            plot_topomap(topo, montage.get_pos(), axes=axes[day + 2*s, 1+ 3*k], show=False, contours=0)


            axes[day + 2*s, 2+ 3*k].plot(*welch(df.loc[df['block_name'].isin(['Rest']), 'smr']*1000000, fs, nperseg=fs*4))
            axes[day + 2*s, 2+ 3*k].plot(*welch(df.loc[df['block_name'].isin(['Left']), 'smr']*1000000, fs, nperseg=fs*4))
            axes[day + 2*s, 2+ 3*k].plot(*welch(df.loc[df['block_name'].isin(['Right']), 'smr']*1000000, fs, nperseg=fs*4))

            if day == 0 and s == 0 and k ==1:
                axes[day + 2*s, 2+ 3*k].legend(['Rest', 'Left', 'Right'])
            axes[day + 2*s, 2+ 3*k].set_xlim(2, 30)
            axes[day + 2*s, 2+ 3*k].set_xlabel('Freq., Hz')
            axes[day + 2*s, 2+ 3*k].set_ylabel('PSD, $\mu V^2/Hz$')

plt.show()