Beispiel #1
0
def plot_sorted_lin_subtracted_(target, lin_subtracted, sorteach, sortind):
    #if fig is None:
    #    fig = plt.figure()
    lin_subtracted_sort = sort_lin_subtracted(lin_subtracted, sorteach,
                                              sortind)
    lb, ub, mn = ut.bootstrap(lin_subtracted_sort[nub_no[sorteach[:, 0]] > 1],
                              axis=0,
                              pct=(16, 84, 50),
                              fn=np.nanmean)
    plt.fill_between(np.arange(1, 33), lb, ub)
    plt.xticks((1, 5, 10, 15, 20, 25, 30))
    plt.xlabel('Stimulus rank')
    plt.ylabel('Normalized linear difference')
    plt.axhline(0, linestyle='dotted', c='k')
    plt.savefig(target, dpi=300)
Beispiel #2
0
def plot_size_tuning(arr, colors=None):
    usize = np.array((0, 5, 8, 13, 22, 36))
    ucontrast = np.array((0, 6, 12, 25, 50, 100))
    arr_sz = gen_size_tuning(arr)
    arr_sz = arr_sz / arr_sz.max(1).max(1)[:, np.newaxis, np.newaxis]
    lb, ub = ut.bootstrap(arr_sz, np.mean, pct=(2.5, 97.5))
    to_plot = arr_sz.mean(0)
    ut.plot_bootstrapped_errorbars_hillel(usize,
                                          arr_sz[:, :, 1::].transpose(
                                              (0, 2, 1)),
                                          colors=colors)
    plt.ylim(to_plot.min() - 0.1, to_plot.max() + 0.1)
    #     plt.title('%d%% contrast' % ucontrast[ic])
    plt.xlabel('size ($^o$)')
    #     plt.subplot(1,2,1)

    plt.tight_layout()
Beispiel #3
0
def plot_size_tuning_by_contrast(arr):
    usize = np.array((0, 5, 8, 13, 22, 36))
    ucontrast = np.array((0, 6, 12, 25, 50, 100))
    arr_sz = gen_size_tuning(arr)
    arr_sz = arr_sz / arr_sz.max(1).max(1)[:, np.newaxis, np.newaxis]
    lb, ub = ut.bootstrap(arr_sz, np.mean, pct=(2.5, 97.5))
    to_plot = arr_sz.mean(0)
    for ic in range(1, 6):
        plt.subplot(1, 5, ic)
        ut.plot_bootstrapped_errorbars_hillel(usize,
                                              arr_sz[:, :, ic].transpose(
                                                  (0, 2, 1)),
                                              colors=['k', 'r'],
                                              markersize=5)
        #         plt.scatter((0,),to_plot[:,0,0].mean(0))
        #         plt.scatter((0,),to_plot[:,0,1].mean(0))
        plt.ylim(0.5 * to_plot.min(), 1.2 * to_plot.max())
        plt.title('%d%% contrast' % ucontrast[ic])
        plt.xlabel('size ($^o$)')
    plt.subplot(1, 5, 1)
    plt.ylabel('event rate / max event rate')
    plt.tight_layout()
Beispiel #4
0
def scatter_size_contrast_errorbar(animal_data,
                                   pct=(16, 84),
                                   mn_plot=None,
                                   mx_plot=None,
                                   opto_color='b',
                                   equality_line=True,
                                   square=True,
                                   xlabel=None,
                                   ylabel=None,
                                   alpha=1,
                                   equate_0=False,
                                   linewidth=1):
    if xlabel is None:
        xlabel = 'PC event rate, light off'
    if ylabel is None:
        ylabel = 'PC event rate, light on'
    this_animal_data = animal_data.copy()
    if equate_0:
        this_animal_data[:, :, 0] = animal_data[:, :, 0].mean(1)[:, np.newaxis]
    lb, ub, mn = ut.bootstrap(this_animal_data,
                              pct=pct + (50, ),
                              fn=np.nanmean,
                              axis=0)
    stats = ut.bootstat(this_animal_data,
                        fns=[compute_slope_w_intercept_, compute_intercept_])
    #print('animal data shape: '+str(this_animal_data.shape))
    #print('stats shape: '+str([s.shape for s in stats]))
    npt = mn[:, :, 0].size
    xerr = np.zeros((2, npt))
    xerr[0] = mn[:, :, 0].flatten() - lb[:, :, 0].flatten()
    xerr[1] = ub[:, :, 0].flatten() - mn[:, :, 0].flatten()
    yerr = np.zeros((2, npt))
    yerr[0] = mn[:, :, 1].flatten() - lb[:, :, 1].flatten()
    yerr[1] = ub[:, :, 1].flatten() - mn[:, :, 1].flatten()
    if mx_plot is None:
        mx_plot = 1.1 * np.nanmax(mn)
    if mn_plot is None:
        mn_plot = np.nanmin(mn)
    xx = np.linspace(mn_plot, mx_plot, 100)[:, np.newaxis]
    #print([s.shape for s in stats])
    YY = xx * stats[0] + stats[1]
    lb_YY = np.nanpercentile(YY, 16, axis=1)
    ub_YY = np.nanpercentile(YY, 84, axis=1)
    mn_YY = np.nanpercentile(YY, 50, axis=1)
    plt.fill_between(xx[:, 0],
                     lb_YY,
                     ub_YY,
                     alpha=0.5 * alpha,
                     facecolor=opto_color)
    plt.plot(xx[:, 0], mn_YY, c=opto_color, alpha=alpha, linewidth=linewidth)
    plt.errorbar(mn[:, :, 0].flatten(),
                 mn[:, :, 1].flatten(),
                 xerr=xerr,
                 yerr=yerr,
                 fmt='none',
                 zorder=1,
                 c='k',
                 alpha=0.5 * alpha)
    sca.scatter_size_contrast(mn[:, :, 0],
                              mn[:, :, 1],
                              equality_line=equality_line,
                              square=square,
                              alpha=alpha,
                              equate_0=equate_0)
    plt.xlabel(xlabel)
Beispiel #5
0
def analyze_size_contrast(datafiles,
                          stimfile,
                          retfile=None,
                          frame_adjust=None,
                          rg=(1, 0),
                          nbefore=nbefore,
                          nafter=nafter,
                          criterion=None,
                          criterion_cutoff=None):
    if criterion is None:
        criterion = lambda x: np.abs(x) > 100
    nbydepth = get_nbydepth(datafiles)
    #     trialwise,ctrialwise,strialwise = gen_trialwise(datafiles,frame_adjust=frame_adjust)
    trialwise, ctrialwise, strialwise, dfof, straces, dtrialwise, trialwise_t_offset = ut.gen_precise_trialwise(
        datafiles,
        rg=rg,
        frame_adjust=frame_adjust,
        nbefore=nbefore,
        nafter=nafter)
    zstrialwise = sst.zscore(strialwise.reshape(
        (strialwise.shape[0], -1)).T).T.reshape(strialwise.shape)

    result = sio.loadmat(stimfile, squeeze_me=True)['result'][()]

    infofile = sio.loadmat(datafiles[0][:-12] + '.mat',
                           squeeze_me=True)  # original .mat file
    frame = infofile['info'][()]['frame'][()]
    frame = frame[rg[0]:frame.size + rg[1]]
    if frame_adjust:
        frame = frame_adjust(frame)

    data = strialwise  #[:,:,nbefore:-nafter]

    try:
        dxdt = sio.loadmat(datafiles[0], squeeze_me=True)['dxdt']
    except:
        with h5py.File(datafiles[0], mode='r') as f:
            dxdt = f['dxdt'][:].T

    trialrun = np.zeros(frame[0::2].shape)
    for i in range(len(trialrun)):
        trialrun[i] = np.abs(dxdt[frame[0::2][i]:frame[1::2][i]]).mean()
    runtrial = criterion(trialrun)
    print(runtrial.sum() / runtrial.size)
    if criterion_cutoff:
        if runtrial.sum() / runtrial.size < criterion_cutoff:
            #return Savg,Smean,lb,ub,pval,spont,Smean_stat,proc
            return [np.array(())] * 8

    #pval = np.zeros(strialwise.shape[0])
    #for i in range(strialwise.shape[0]):
    #    _,pval[i] = sst.ttest_rel(data[i,:,nbefore-1],data[i,:,nbefore+1])

    stimparams = result['stimParams']
    gratingInfo = result['gratingInfo']

    indexlut, stimp = np.unique(stimparams, axis=1, return_inverse=True)

    #angle = stimparams[0]
    #size = stimparams[1]
    #contrast = stimparams[4]
    #light = stimparams[5]

    angle = gratingInfo['Orientation'][()]
    size = gratingInfo['Size'][()]
    contrast = gratingInfo['Contrast'][()]
    light = gratingInfo['lightsOn'][()]

    ucontrast = np.unique(contrast)
    uangle = np.unique(angle[~np.isnan(angle)])
    usize = np.unique(size)
    ulight = np.unique(light)
    ncontrast = len(ucontrast)
    nangle = len(uangle)
    nsize = len(usize)
    nlight = len(ulight)
    print(nlight)

    angle180 = np.remainder(angle, 180)
    uangle180 = np.unique(angle180[~np.isnan(angle180)])
    nangle180 = len(uangle180)

    Smean = np.zeros(
        (data.shape[0], nangle180, nsize, ncontrast, nlight, data.shape[2]))
    Smean_stat = np.zeros(
        (data.shape[0], nangle180, nsize, ncontrast, nlight, data.shape[2]))
    Stavg = np.zeros(
        (data.shape[0], nangle180, nsize, ncontrast, nlight,
         int(data.shape[1] / nangle / nsize / ncontrast / nlight)))

    Strials = {}
    Sspont = {}
    for i in range(nangle180):
        for j in range(nsize):
            for k in range(ncontrast):
                for ii in range(nlight):
                    lkat = np.logical_and(
                        np.logical_and(
                            runtrial,
                            np.logical_and(
                                angle180 == uangle180[i],
                                np.logical_and(size == usize[j],
                                               contrast == ucontrast[k]))),
                        light == ulight[ii])
                    Smean[:, i, j, k, ii, :] = data[:, lkat, :].mean(1)
                    Strials[(i, j, k, ii)] = data[:, lkat,
                                                  nbefore:-nafter].mean(2)
                    Sspont[(i, j, k, ii)] = data[:, lkat, :nbefore].mean(2)
                    stat = np.logical_and(
                        np.logical_and(
                            np.logical_not(runtrial),
                            np.logical_and(
                                angle180 == uangle180[i],
                                np.logical_and(size == usize[j],
                                               contrast == ucontrast[k]))),
                        light == ulight[ii])
                    Smean_stat[:, i, j, k, ii] = data[:, stat].mean(1)

    lb = np.zeros((strialwise.shape[0], nangle180, nsize, ncontrast, nlight))
    ub = np.zeros((strialwise.shape[0], nangle180, nsize, ncontrast, nlight))
    # mn = np.zeros((strialwise.shape[0],nangle180,nsize,ncontrast))

    for i in range(nangle180):
        for j in range(nsize):
            for k in range(ncontrast):
                for ii in range(nlight):
                    if Strials[(i, j, k, ii)].size:
                        lb[:, i, j, k,
                           ii], ub[:, i, j, k,
                                   ii] = ut.bootstrap(Strials[(i, j, k, ii)],
                                                      np.mean,
                                                      axis=1,
                                                      pct=(16, 84))
                    else:
                        lb[:, i, j, k, ii] = np.nan
                        ub[:, i, j, k, ii] = np.nan
                # mn[:,i,j,k] = np.nanmean(Strials[(i,j,k)],axis=1)

    pval = np.zeros((strialwise.shape[0], nangle180))
    #     for i in range(pval.shape[0]):
    #         print(i)
    for j, theta in enumerate(uangle180):
        _, pval[:, j] = sst.ttest_rel(Sspont[(j, 0, ncontrast - 1, 0)],
                                      Strials[(j, 0, ncontrast - 1, 0)],
                                      axis=1)

    Savg = np.nanmean(np.nanmean(Smean[:, :, :, :, :, nbefore:-nafter],
                                 axis=-1),
                      axis=1)

    Storiavg = Stavg.mean(1)
    # _,pval = sst.ttest_ind(Storiavg[:,0,-1].T,Storiavg[:,0,0].T)

    #suppressed = np.logical_and(pval<0.05,Savg[:,0,-1]<Savg[:,0,0])
    #facilitated = np.logical_and(pval<0.05,Savg[:,0,-1]>Savg[:,0,0])
    spont = np.zeros((Savg.shape[0], ))
    keylist = list(Sspont.keys())
    nkeys = len(keylist)
    for key in Sspont.keys():
        spont = spont + Sspont[key].mean(1) / nkeys

    proc = {}
    proc['runtrial'] = runtrial
    proc['trialrun'] = trialrun
    proc['angle'] = angle
    proc['size'] = size
    proc['contrast'] = contrast
    proc['light'] = light
    proc['trialwise'] = trialwise
    proc['strialwise'] = strialwise
    #proc['ctrialwise'] = ctrialwise
    proc['dtrialwise'] = dtrialwise
    proc['trialwise_t_offset'] = trialwise_t_offset
    proc['dfof'] = dfof
    proc['frame'] = frame

    return Savg, Smean, lb, ub, pval, spont, Smean_stat, proc