示例#1
0
文件: uts.py 项目: kriek197/Eelbrain
def corr(stats, var, p=[.05],
         figsize=(6.,4.),
         axrect=[.08,.15,.9,.75],
         legend_ncol=4,
         ):
    """
    plots the correlation between a timeseries and a variable over time
    
    """
#    if iscollection(stats):
#        stats = [stats]
#    assert all(iscollection(s) for s in stats)
    corr = [segment_ops.corr(s, var) for s in stats] 
    
    if np.isscalar(p):
        p = [p]
    # P (http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Inference)
    n = len(corr[0]['slist'])
    if not all([len(corr[i]['slist']) == n for i in range(1, len(corr))]):
        raise ValueError("StatsSegments have different N --> p threshold cannot be drawn correctly")
    Ps = np.array(p) / 2 # 2 tailed
    df = n-2
    Ts = sp.stats.t.isf(Ps, df)
    R_thresholds = Ts / np.sqrt(df + Ts**2)
    
    P.figure(figsize=figsize)
    ax = P.axes(axrect)
    legend_names = []
    legend_handles = []
    # corr
    T = stats[0].t
    for c in corr:
        R = c.param
        handle = P.plot(T, R, label=c.name)
        legend_names.append(fmtxt.texify(c.name))
        legend_handles.append(handle)
    # thresholds
    P.axhline(0, c='k')
    for p in R_thresholds:
        P.axhline(p)
        P.axhline(-p)
    # Figure stuff
    P.ylabel('r')
    P.xlabel('time')
    P.suptitle("Correlation with {v}".format(v=fmtxt.texify(var.name)), fontsize=16)
    P.figlegend(legend_handles, legend_names, 'lower center', ncol=legend_ncol)
示例#2
0
def _ax_im_array(ax, layers, title=None, tick_spacing=.5):
    """
    plots segment data as im
    
    define a colorspace by supplying one of those kwargs: ``colorspace`` OR 
    ``p`` OR ``vmax``
    
    """
    handles = []
    epoch = layers[0]
    
    map_kwargs = {'extent': [epoch.time[0], epoch.time[-1], 0, len(epoch.sensor)],
                  'aspect': 'auto'}
    
    # plot
    for l in layers:
        h = _plt_im_array(ax, l, **map_kwargs)
        handles.append(h)
    
    ax.set_ylabel("Sensor")
    ax.set_xlabel("Time [s]")
    
    #ticks
    tickstart = int((-epoch.time[0] - 1e-3) / tick_spacing)
    ticklabels = np.r_[-tickstart * tick_spacing :  \
                       epoch.time[-1] + 1e-3 : tick_spacing]
    ax.xaxis.set_ticks(ticklabels)
    
    #title
    if title is None:
        if _plt.rcParams['text.usetex']:
            title = fmtxt.texify(epoch.name)
        else:
            title = epoch.name
    ax.set_title(title)
    
    return handles
示例#3
0
    def plot(self, fig_num=None):#, tmax=1000):
        if self._example_path == None:
            ui.message("No files specified", "Before an import preview can be "
                       "plotted, at least one source file has "
                       "to be specified through the p.source parameter.", '!')
            return
        
        data = self._example_data#[:tmax]
        
        # range correct data
        t, n = data.shape
        data = data - np.min(data, 0)
        data /= np.max(data, 0) * 1.1
        data += np.arange(n-1, -1, -1) # channel 1 on the top
        
        # collect properties
        name = os.path.basename(self._example_path)
        samplingrate = self.p.samplingrate.get()
        T = np.arange(0, t)
        if samplingrate:
            T /= samplingrate
        
        # start plot
        P.figure(fig_num)
        P.subplots_adjust(.2, .05, .99, .9)
        P.suptitle("Example: %s"%fmtxt.texify(name))
        ax = P.axes()
        lines = [ax.plot(data[:,i], c='.75', antialiased=False)[0] for i in xrange(n)]
        y_ticks = np.arange(n-1, -1, -1) + .45
        y_ticklabels = range(n)        
        # get channels data
        for index, settings in self.p.channels.iterchannels():
#            ax = P.subplot(n, 1, i+1, sharex=ax)
            name, ds_type, arg1, arg2 = settings
            
#            y_ticklabels.append(name)
            if isinstance(index, int):
                ls = [lines[index]]
                y_ticklabels[index] = name
#                y_ticks.append(i)
            else:
                if isinstance(index, slice):
                    start, stop = index.start, index.stop
                    ls = lines[index]
                    indexes = xrange(start+1, stop+1)
                else:
                    start = index[0]
                    indexes = index[1:]
                    ls = [lines[i] for i in index]
                y_ticklabels[start] = name
                for i in indexes:
                    y_ticklabels[i] = ''
#                tick_y = start + (stop-start)//2
#                y_ticks.append(tick_y)
            
            if ds_type == 'uts':
                c = 'k'
            elif ds_type == 'topo':
                c = 'r'
            elif ds_type == 'evt':
                c = 'b'
            
            for l in ls:
                l.set_color(c)
        
        if hasattr(ax, 'tick_params'):
            ax.tick_params(axis='y', length=0)
        
        ax.set_xlim(0, len(data))
        ax.set_yticks(y_ticks)
        ax.set_yticklabels(y_ticklabels)
#        ax.set_xlim(T[0], T[-1])
#        ax.set_xlim(0, tmax)
        P.show()
示例#4
0
def _ax_im_array(ax, layers, x='time',  # vmax=None,
                 xlabel=True, ylabel=True, title=None, tick_spacing=.3):
    """
    plots segment data as im

    define a colorspace by supplying one of those kwargs: ``colorspace`` OR
    ``p`` OR ``vmax``

    """
    handles = []
    epoch = layers[0]

    xdim = epoch.get_dim(x)
    if epoch.ndim == 2:
        xdim_i = epoch.dimnames.index(x)
        ydim_i = {1:0, 0:1}[xdim_i]
        y = epoch.dimnames[ydim_i]
    else:
        err = ("Need 2 dimensions, got %i" % epoch.ndim)
        raise ValueError(err)

    ydim = epoch.get_dim(y)
    if y == 'sensor':
        ydim = _dta.var(np.arange(len(ydim)), y)

    map_kwargs = {'extent': [xdim[0], xdim[-1], ydim[0], ydim[-1]],
                  'aspect': 'auto'}

    # plot
    for l in layers:
        h = _plt_im_array(ax, l, dims=(y, x), **map_kwargs)
        handles.append(h)

    if xlabel:
        if xlabel is True:
            xlabel = xdim.name
        ax.set_xlabel(xlabel)

    if ylabel:
        if ylabel is True:
            ylabel = ydim.name
        ax.set_ylabel(ylabel)

    # x-ticks
    tickstart = math.ceil(xdim[0] / tick_spacing) * tick_spacing
    tickend = xdim[-1] + tick_spacing / 1e4
    ticklabels = np.arange(tickstart, tickend, tick_spacing)
    ax.xaxis.set_ticks(ticklabels)
    ax.x_fmt = "t = %.3f s"

    # y-ticks
    if y == 'sensor':  # make sure y-ticklabels are all integers
        locs = ax.yaxis.get_ticklocs()
        if any(locs != locs.round()):
            idx = np.where(locs == locs.round())[0]
            locs = locs[idx]
            labels = map(lambda x: str(int(x)), locs)
            ax.yaxis.set_ticks(locs)
            ax.yaxis.set_ticklabels(labels)

    # title
    if title is None:
        if plt.rcParams['text.usetex']:
            title = fmtxt.texify(epoch.name)
        else:
            title = epoch.name
    ax.set_title(title)

    return handles
示例#5
0
def _get_attributes(statsSegments, sensor=None):
    ""
    raise DeprecationWarning
    if sensor:
        try:
            sensor_name = statsSegments[0].sensors[sensor].name
        except Exception, exc:
            print Exception, exc
            sensor_name = None
    else:
        sensor_name = None
    seg_t_start = statsSegments[0].tstart
    seg_t_end = statsSegments[0].tend
    
    if P.rcParams['text.usetex']:
        names = [fmtxt.texify(s.name) for s in statsSegments]
    else:
        names = [s.name for s in statsSegments]
    
    return names, sensor_name, seg_t_start, seg_t_end



# MARK: figure composition

def _loc(name, size=(0,0), title_space=0, frame=.01):
    """
    takes a loc argument and returns x,y of bottom left edge
    
    """
    if isinstance(name, basestring):