示例#1
0
def horiz_time_const(d, params):
    '''
    TO DO:
    '''

    fig = plt.figure()
    fig.set_tight_layout(True)
    ax = fig.add_subplot(111)
    pf.AxisFormat()
    pf.TufteAxis(ax, ['bottom', 'left'], [3, 3])

    time = util.get_time(d)
    inds = np.where(np.logical_and(time >= 450, time <= 600))[0]

    time_ = time[inds] - 500

    for t in range(d['ntrial']):
        h1 = util.get_cell_data(d['tr'][t], 'h1')
        h2 = util.get_cell_data(d['tr'][t], 'h2')

        h1dat = d['tr'][t]['r'][h1[0]]['x'][inds]
        h2dat = d['tr'][t]['r'][h2[0]]['x'][inds]

        ax.plot(time_, h1dat, label='H1')  # only use 1st response
        ax.plot(time_, h2dat, label='H2')  # only use 1st response

    #ax[1].set_ylabel('response')
    ax.set_xlabel('time (ms)')
    ax.legend(fontsize=22, loc='lower right')

    savedir = util.get_save_dirname(params, check_randomized=True)
    fig.savefig(savedir + 'h_time_const' + str(t) + '.eps', edgecolor='none')
    plt.show(block=params['block_plots'])
示例#2
0
def s_cone_weights(d, celllist, celldat, params):
    '''
    '''

    lm_midgets = an.compute_s_dist_cone_weight(d, celldat, celllist, params)

    # plotting routines    
    ax, fig1 = pf.get_axes(1, 1, nticks=[4, 5], return_fig=True)
    ax[0].plot(lm_midgets[:, 0], lm_midgets[:, 1], 'ko')

    ax[0].set_xlabel('distance from S-cone (arcmin)')
    ax[0].set_ylabel('S / (L+M+S)')

    # histogram of same data
    ax2, fig2 = pf.get_axes(1, 1, nticks=[4, 5], return_fig=True)
    ax2[0].spines['bottom'].set_smart_bounds(False)

    count, bins = np.histogram(lm_midgets[:, 1], bins=15)
    count = count / count.sum() * 100
    bins, count = pf.histOutline(count, bins)
    ax2[0].plot(bins, count, 'k-')

    ax2[0].set_xlim([0, 1])
    ax2[0].set_ylabel('% of cells')
    ax2[0].set_xlabel('S / (L+M+S)')

    # Save plots
    savedir = util.get_save_dirname(params, check_randomized=True)
    fig1.savefig(savedir + 's_weight_scatter.eps', edgecolor='none')
    fig2.savefig(savedir + 's_weight_hist.eps', edgecolor='none')
示例#3
0
def dist(data, params, normalize=True):
    '''
    '''
    deg_per_pix, mm_per_deg = util.conversion_factors(params['species'])

    fig = plt.figure(figsize=(5.5, 6))
    fig.set_tight_layout(True)
    ax = fig.add_subplot(111)

    pf.AxisFormat(markersize=8, linewidth=3)
    pf.TufteAxis(ax, ['bottom', 'left'], [4, 5])

    for d in data:
        dat = data[d]
        dat = dat[dat[:, 0].argsort()]

        x_val_h = dat[:, 0] * deg_per_pix * mm_per_deg * 1000
        yval = dat[:, 1]

        xval = np.hstack([x_val_h[::-1][:-1] * -1, x_val_h])
        yval = np.hstack([yval[::-1][:-1], yval])
        if normalize:
            yval /= yval.max()

        ax.plot(xval, yval, '-', label=d.upper())

    ax.set_xlabel('distance ($\mu$m)')
    ax.set_xlim([-200, 200])
    ax.legend(fontsize=22)

    savedir = util.get_save_dirname(params, check_randomized=True)
    fig.savefig(savedir + 'h_space_const.svg', edgecolor='none')
    plt.show(block=params['block_plots'])
示例#4
0
def mosaic(params, return_ax=False):

    mosaic = np.genfromtxt(params['mosaic_file'])
    fig = plt.figure(figsize=(9, 9))
    fig.set_tight_layout(True)
    ax = fig.add_subplot(111)
    
    pf.AxisFormat()
    pf.TufteAxis(ax, [''], [5, 5])

    s_cones = mosaic[np.where(mosaic[:, 1] == 0)[0]]
    m_cones = mosaic[np.where(mosaic[:, 1] == 1)[0]]
    l_cones = mosaic[np.where(mosaic[:, 1] == 2)[0]]
    
    ax.plot(s_cones[:, 2], s_cones[:, 3], 'bo', markersize=6)
    ax.plot(m_cones[:, 2], m_cones[:, 3], 'go', markersize=6)
    ax.plot(l_cones[:, 2], l_cones[:, 3], 'ro', markersize=6)
    
    ax.set_xlim([-1, 128])
    ax.set_ylim([-1, 128])

    if not return_ax:
        savedir = util.get_save_dirname(params, check_randomized=True)
        fig.savefig(savedir + 'mosaic.eps', edgecolor='none')
        plt.show(block=params['block_plots'])

    else:
        return ax, fig
示例#5
0
def plot_cone_weights(r, celldat, celllist, params):
    '''
    '''
    fig = plt.figure(figsize=(6,6))
    fig.set_tight_layout(True)
    ax = fig.add_subplot(111)

    # build diamond plot
    pf.AxisFormat(markersize=8, fontsize=9, tickdirection='inout')
    pf.centerAxes(ax)
    ax.spines['left'].set_smart_bounds(False)
    ax.spines['bottom'].set_smart_bounds(False)
    ax.axis('equal')

    # Add in diamond boarders
    ax.plot([-1, 0], [0, 1], 'k')
    ax.plot([0, 1], [1, 0], 'k')
    ax.plot([1, 0], [0, -1], 'k')
    ax.plot([0, -1], [-1, 0], 'k')

    # set come fig params
    ax.set_xlim([-1.1, 1.1])
    ax.set_ylim([-1.1, 1.1])

    # get mosaic plot
    mos, mos_fig = mosaic(params, return_ax=True)
    for c in r: # for each cell type in results
        for cone in range(0, len(r[c][:, 0])):
            ind = np.where(celldat[:, 0] == float(celllist[cone]))[0]
            type = round(celldat[ind, 1])
            sym = find_shape_color(type, c)
            loc = celldat[ind, 2:4][0]

            # add data to diamond plot
            ax.plot(r[c][cone, 2], r[c][cone, 1], sym)
            ax.plot(-r[c][cone, 2], -r[c][cone, 1], sym, mec='k', mew=2,
                     alpha=0.5)

            # compute s weight for mosaic plot
            s_weight = r[c][cone, 0] #compute_s_weight(r, c, cone)
            
            s_rgb = 1 - np.abs(s_weight)
            mos.plot(loc[0], loc[1], 'o', fillstyle='none', mew=4,
                     mec=[s_rgb, s_rgb, s_rgb])

    mos.set_xlim([35, 90])
    mos.set_ylim([35, 90])

    # save figs
    savedir = util.get_save_dirname(params, check_randomized=True)
    fig.savefig(savedir + 'cone_inputs.svg', edgecolor='none')
    mos_fig.savefig(savedir + 'cone_inputs_mosaic.eps', edgecolor='none')
示例#6
0
def knn(d, params):
    '''
    TO DO:

    '''
    celllist = util.get_cell_list(d)
    celldat = np.genfromtxt('results/txt_files/nn_results.txt')
    cellIDs = celldat[:, 0]

    fig = plt.figure()
    fig.set_tight_layout(True)
    ax = fig.add_subplot(111)

    pf.AxisFormat(markersize=8)
    pf.TufteAxis(ax, ['bottom', 'left'], [5, 5])

    N = util.num(d['const']['MOO_tn']['val'])  # time steps
    tf = util.num(d['const']['tf']['val'])  # temporal frequency (Hz)

    keys = util.get_cell_data(d['tr'][0], 'h2')
    for i, r in enumerate(keys):
        # find distance to S
        cellID = int(celllist[i])
        ind = np.where(cellIDs == cellID)[0]
        distance = celldat[ind, 4][0]

        # find amplitude of signal
        cell = d['tr'][0]['r'][r]['x']
        fft = np.fft.fft(cell)
        amp = np.abs(fft[tf]) * 2 / N

        if celldat[ind, 1] == 0:
            ax.plot(distance, amp, 'bo')
        if celldat[ind, 1] == 1:
            ax.plot(distance, amp, 'go')
        if celldat[ind, 1] == 2:
            ax.plot(distance, amp, 'ro')

    savedir = util.get_save_dirname(params, check_randomized=True)
    fig.savefig(savedir + 'knn.svg', edgecolor='none')
    plt.show(block=params['block_plots'])
示例#7
0
def s_cone_dist_analysis(rg, results, model_name):
    '''
    '''
    # checkout proximity to s cone and rg metric
    ax, fig = pf.get_axes(1, 1, nticks=[3, 3], return_fig=True)
    ax = ax[0]
    inds = results[:, 4] < 0.4 # eliminate S-cone center cells
    ax.plot(results[inds, 4], np.abs(rg[inds]), 'ko')
    
    ax.set_xlabel('S-cone weight')
    ax.set_ylabel('absolute value rg response')

    # See if there is a relationship between color names and distance to S-cone
    X = sm.add_constant(results[inds, 4], prepend=True)
    OLSmodel = sm.OLS(rg[inds], X)
    res = OLSmodel.fit()
    print '\n\n\n'
    print res.rsquared

    savedir = util.get_save_dirname(params, check_randomized=True)
    fig.savefig(savedir + 's_cone_distance.svg', edgecolor='none')    
示例#8
0
def plot_color_names(rg, purity_thresh, results, params):
    '''
    '''
    # --- plot color names on a diamond plot --- #
    fig1 = plt.figure(figsize=(6,6))
    fig1.set_tight_layout(True)
    ax = fig1.add_subplot(111)

    # build diamond plot
    pf.AxisFormat(markersize=8, fontsize=20)
    pf.centerAxes(ax)
    ax.spines['left'].set_smart_bounds(False)
    ax.spines['bottom'].set_smart_bounds(False)
    ax.axis('equal')

    # Add in diamond boarders
    ax.plot([-1, 0], [0, 1], 'k')
    ax.plot([0, 1], [1, 0], 'k')
    ax.plot([1, 0], [0, -1], 'k')
    ax.plot([0, -1], [-1, 0], 'k')

    for i in range(len(rg)):
        maxind = results[i, 5:10].argmax()
        symbol = 'o'
        # check if cone has a purity greater threshold
        if purity_thresh is not None and purity_thresh < 1:
            symbol = '^' # means low purity

        if rg[i] < 0:
            color = [0, np.abs(rg[i]), 0]
        else:
            color = [np.abs(rg[i]), 0, 0]

        ax.plot(results[i, 3], results[i, 2], symbol, color=color,
                 markeredgewidth=2, markeredgecolor='k', alpha=0.5)

    savedir = util.get_save_dirname(params, check_randomized=True)
    fig1.savefig(savedir + 'cone_inputs_w_naming.svg',
                edgecolor='none')
示例#9
0
def fit_linear_model(rg, results, params, opponent=True):
    # Switch depending upon opponent option
    if not opponent:
        predictors = results[:, [2, 3, 4, 10, 11, 12, 13, 14, 15, 16, 17, 18, 
                                19, 20, 21, 22, 23, 24, 25, 26, 27]] 
    else:
        # organize in opponent fashion
        N = 2 # center cone and nearest x
        predictors = np.zeros((len(results[:, 0]), N + 1))
        _inds = [2, 10, 13, 16, 19, 22, 25, 28, 31]
        for i in range(N + 1):
            predictors[:, i] = ((results[:, _inds[i]] +
                                 results[:, _inds[i] + 2])
                                - results[:, _inds[i] + 1])
    # cone weights in L, M, S order
    inds = [2, 10, 13]
    X = sm.add_constant(predictors, prepend=True)
    OLSmodel = sm.OLS(rg, X) #GLM(rg, X)
    res = OLSmodel.fit()
    #print res.rsquared
    print '\n\n\n'
    print (res.summary())

    linear_reg = True
    ridge_reg = False

    ## Linear regression on training data
    clfs = []
    if linear_reg:
        clfs.append(LinearRegression())
    if ridge_reg:
        clfs.append(Ridge())

    ax, fig = pf.get_axes(1, 1, nticks=[3, 3], return_fig=True)
    ax = ax[0]
    Ntrials = 100
    mae = np.zeros((Ntrials, 1))
    for i in range(Ntrials):
        x_train, x_test, y_train, y_test = model_selection.train_test_split(
            predictors, rg, test_size=0.15)

        for clf in clfs:

            clf.fit(x_train, y_train) 
            mae[i] = mean_absolute_error(y_test, clf.predict(x_test))    

            ax.plot(y_test, clf.predict(x_test), 'ko', alpha=0.5)

    print '\n\n'
    print mae.mean(), mae.std()

    ax.set_xlabel('observed')
    ax.set_ylabel('predicted')
    ax.set_aspect('equal')

    if y_train.min() < 0:
        ax.plot([-1, 1], [-1, 1], 'k-')
        ax.set_ylim([-1, 1])
        ax.set_xlim([-1, 1])
    else:
        ax.plot([0, 1], [0, 1], 'k-')
    savedir = util.get_save_dirname(params, check_randomized=True)
    fig.savefig(params + 'cone_inputs_model_error.svg',
                edgecolor='none')
示例#10
0
def classify_analysis(d, params, purity_thresh=0.0, nseeds=10):
    '''
    '''
    # --- params --- #
    rg_metric = False
    background = 'white'
    cmdscaling = True
    # kernel options=linear, rbf, poly
    kernel = 'linear'

    # MDScaling options
    dims = [0, 1]
    test_size = 0.15
    # if kernel is set to linear only first entry of 'C' is used, gamma ignored
    param_grid = {'C': [1e9],
                  'gamma': [0.0001, 0.001], }
    # -------------- #
    human_subjects = ['wt', 'bps']
    if params['model_name'].lower() not in human_subjects:
        raise('Model must be a human subject with psychopysics data')

    # no need to run a bunch of times since lms is easy to classify    
    if not params['color_cats_switch']:
        nseeds = 1 

    # get some info about the cones
    nn_dat = util.get_nn_dat(params['model_name'])
    celllist = util.get_cell_list(d)
    ncells = len(celllist)
    
    # put responses into a matrix for easy processing
    data_matrix = an.get_data_matrix(d, params['cell_type'])

    # compute distance matrix
    corrmat = an.compute_corr_matrix(data_matrix)

    if cmdscaling:
        # compute the classical multi-dimensional scaling
        config_mat, eigen = dat.cmdscale(corrmat)
    else:
        pca = PCA(n_components=len(dims)).fit(data_matrix)
        config_mat = pca.transform(data_matrix)

    # get the location and cone type of each cone
    xy_lms = an.get_cone_xy_lms(d, nn_dat, celllist)

    # threshold rg that separates red, white, green
    if params['color_cats_switch']:
        # get response
        cone_contrast=params['cone_contrast']
        r = an.response(d, params)
        output = an.associate_cone_color_resp(r, nn_dat, celllist, params['model_name'], 
                                              bkgd=background, 
                                              randomized=params['randomized'])
        stim_cone_ids = output[:, -1]
        stim_cone_inds = np.zeros((1, len(stim_cone_ids)), dtype='int')
        for cone in range(len(stim_cone_ids)):
            stim_cone_inds[0, cone] = np.where(nn_dat[:, 0] == 
                                               stim_cone_ids[cone])[0]

        if rg_metric:
            # break rg into three categories: red, green, white
            rg, by, high_purity = an.get_rgby_from_naming(output[:, 5:10], 
                                                          purity_thresh)
            rgby_thresh = 0.5
            red = rg < -rgby_thresh
            green = rg > rgby_thresh
            blue = by < -rgby_thresh
            yellow = by > rgby_thresh
            color_categories = (yellow * 4 + blue * 3 + red * 2 + green).T[0]

        else: # use dom response category
            max_cat = np.argmax(output[:, 5:10], axis=1)
            red = max_cat == 1
            green = max_cat == 2
            blue = max_cat == 3
            yellow = max_cat == 4
            color_categories = (yellow * 4 + blue * 3 + red * 2 + green).T

        class_cats = color_categories.copy()
        config_mat = config_mat[stim_cone_inds, :][0]
        data_matrix = data_matrix[stim_cone_inds, :][0]
        ncells = len(class_cats)
    else:
        class_cats = xy_lms[:, 2]

    # SVM Classify
    print 'running SVM'
    print '\tCMDScaling=' + str(cmdscaling)
    print '\tkernel=' + str(kernel)
    print '\tRGmetric=' + str(rg_metric)
    print '\tbackground=' + background

    target_names, class_cats = get_target_names_categories(params['color_cats_switch'], 
                                                           class_cats)
    clf, report = an.svm_classify(data_matrix, class_cats, param_grid, target_names, 
                          cmdscaling, dims=dims, display_verbose=True, 
                          rand_seed=2264235, Nseeds=nseeds, test_size=test_size,
                          kernel=kernel)
    print report

    # --------------------------------------------------- #
    print 'plotting results from SVM'

    # undo category shift of plotting 
    if background == 'blue' and params['color_cats_switch']:
        class_cats[class_cats > 0] += 1

    # need to order corrmat based on color category
    sort_inds = np.argsort(class_cats)
    sort_data_matrix = data_matrix[sort_inds, :]
    sort_corrmat = an.compute_corr_matrix(sort_data_matrix)
    # plot correlation matrix
    ax, fig1 = pf.get_axes(1, 1, nticks=[3, 3], return_fig=True)    
    ax[0].imshow(sort_corrmat)
    # change axes to indicate location of category boundaries

    # plot MDS configuration matrix in 2 and 3dim
    ax, fig2 = pf.get_axes(1, 1, nticks=[3, 3], return_fig=True)
    # add decision function
    xx, yy = np.meshgrid(np.linspace(-1.5, 1.5, 200), np.linspace(-1.5, 1.5, 200))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    ax[0].contourf(xx, yy, -Z, cmap=plt.cm.Paired, alpha=0.8)
                         
    for cone in range(ncells):
        if (class_cats[cone] == 0 and params['color_cats_switch'] is False 
            or class_cats[cone] == 3):
            color = [0, 0, 1]
        elif class_cats[cone] == 0 and params['color_cats_switch'] is True:  
            color = [0.7, 0.7, 0.7]
        elif class_cats[cone] == 1:
            color = [0, 1, 0]
        elif class_cats[cone] == 2:
            color = [1, 0, 0]
        elif class_cats[cone] == 4:
            color = [0.8, 0.8, 0] # yellow
        else:
            raise TypeError('category type must be int [0, 4]')

        ax[0].plot(config_mat[cone, 0], config_mat[cone, 1], 'o', markersize=8,
                   alpha=0.8, color=color, markeredgecolor='k')


    # save output
    savedir = util.get_save_dirname(params, check_randomized=True)
    # save txt file
    fhandle = open(savedir + 'classification_report.txt', 'w')
    fhandle.write(report)
    fhandle.close()

    # save figs
    #fig1.savefig(savename + '_corr_matrix.eps', edgecolor='none')
    fig2.savefig(savedir + 'low_dim_rep.eps', edgecolor='none')
    #fig3.savefig(savename + '_3dplot.eps', edgecolor='none')

    if cmdscaling:
        ax, fig4 = pf.get_axes(1, 1, nticks=[3, 3], return_fig=True)
        ax[0].plot(eigen, 'ko')
        fig4.savefig(savedir + 'eigenvals.eps', edgecolor='none')
    plt.show(block=params['block_plots'])
示例#11
0
def tuning_curve(d, params):
    '''
    '''
    # Get this with conversion call
    deg_per_pix, mm_per_deg = util.conversion_factors(params['species'])
    deg2um = mm_per_deg / 1000  #  conversion (micron / deg)

    if params['analysis_type'] == 'sf':
        figsize = (7, 7)
    else:
        figsize = (6, 5)

    fig = plt.figure(figsize=figsize)
    fig.set_tight_layout(True)
    ax1 = fig.add_subplot(111)
    if params['analysis_type'] == 'sf':
        ax2 = ax1.twiny()

    pf.AxisFormat()
    pf.TufteAxis(ax1, [
        'bottom',
        'left',
    ], [4, 4])
    if params['analysis_type'] == 'sf':
        pf.TufteAxis(ax2, [
            'top',
        ], [4, 4])

    # get the data
    r = an.response(d, params)

    colors = ['k', 'gray', 'r', 'b', 'g', 'c', 'm']
    cells = util.get_cell_type(params['cell_type'])
    # set some smart axes for second axis
    ymax = -100  # start small
    ymin = 1000  # start large
    if params['analysis_type'] == 'sf':
        x = util.num(d['const']['VAR_sf']['val'])  # spatial freq (cpd)
    elif params['analysis_type'] == 'tf':
        x = util.num(d['const']['VAR_tf']['val'])  # temp freq

    for i, c in enumerate(cells):
        ax1.loglog(x, r[c][i, :], 'o-', color=colors[i], label=c)
        vec = np.reshape(r[c], -1)
        max = np.max(vec)
        min = np.min(vec)
        if max > ymax:
            ymax = max
        if min < ymin:
            ymin = min

    ymax += 0.1
    ymin -= 0.1

    ax1.axis([x[0] - 0.05, x[-1] + 1, ymin, ymax])
    ax1.set_ylabel('amplitude')
    ax1.legend(fontsize=22, loc='lower center')

    if params['analysis_type'] == 'tf':
        ax1.set_xlabel('temporal frequency (Hz)')

    elif params['analysis_type'] == 'sf':
        ax1.set_xlabel('cycles / degree')
        ax2.xaxis.tick_top()
        ax2.yaxis.tick_left()
        ax2.axis([(x[0] - 0.05) * deg2um, (x[-1] + 1) * deg2um, ymin, ymax])
        ax2.set_xlabel('cycles / $\mu$m')
        ax2.set_xscale('log')

    savedir = util.get_save_dirname(params, check_randomized=True)
    fig.savefig(savedir + params['cell_type'] + '_' + params['analysis_type'] +
                '_tuning.eps',
                edgecolor='none')
    plt.show(block=params['block_plots'])
示例#12
0
def stack(d, params):
    '''
    TO DO:
    * Add rgc option
    '''

    ylim = [[0, 0], [0, 0], [0, 0]]
    figs = {}
    for t in range(d['ntrial']):
        figs[t] = {}
        figs[t]['f'] = plt.figure(figsize=(6.5, 9))
        figs[t]['f'].set_tight_layout(True)
        ax = {}
        ax[0] = figs[t]['f'].add_subplot(311)
        ax[1] = figs[t]['f'].add_subplot(312)
        ax[2] = figs[t]['f'].add_subplot(313)

        pf.AxisFormat()

        pf.TufteAxis(ax[0], [
            'left',
        ], [3, 3])
        pf.TufteAxis(ax[1], [
            'left',
        ], [3, 3])
        pf.TufteAxis(ax[2], ['bottom', 'left'], [3, 3])

        time = util.get_time(d)
        # Subtract 10 points in so that zero offset
        for i in ax:
            ax[i].set_prop_cycle(
                cycler('color', ['r', 'g', 'b', 'c', 'm', 'y', 'k']))

        keys = util.get_cell_data(d['tr'][t], 'cone')
        for r in keys:
            dat = d['tr'][t]['r'][r]['x']
            y = dat - dat[10]
            ax[0].plot(time, y)
            ylim = check_lims(y, ylim, 0)

        keys = util.get_cell_data(d['tr'][t], 'h1')
        for r in keys:
            dat = d['tr'][t]['r'][r]['x']
            y = dat - dat[10] + 0.2
            ax[1].plot(time, y)
            ylim = check_lims(y, ylim, 1)

        keys = util.get_cell_data(d['tr'][t], 'h2')
        for r in keys:
            dat = d['tr'][t]['r'][r]['x']
            y = dat - dat[10] + 0.1
            ax[1].plot(time, y)
            ylim = check_lims(y, ylim, 1)

        keys = util.get_cell_data(d['tr'][t], 'bp')
        for r in keys:
            dat = d['tr'][t]['r'][r]['x']
            y = dat - dat[10]
            ax[2].plot(time, y)
            ylim = check_lims(y, ylim, 2)

        ax[2].set_xlabel('time (ms)')
        figs[t]['ax'] = ax

    for t in figs:
        for i in ax:
            figs[t]['ax'][i].set_ylim(ylim[i])

        savedir = util.get_save_dirname(params, check_randomized=True)
        for i in ax:
            #pf.invert(ax[i], fig, bk_color='k')
            figs[t]['f'].savefig(savedir + 'stack_t' + str(t) + '.eps',
                                 edgecolor='none')

    plt.show(block=params['block_plots'])