def normalized_hist_dataframe(data_column,
                              bin_number=50,
                              output_dir='/var/tmp/'):
    """
    Create a histogram using 2019AStrpi database with just the column name as an input
    Args:
        data_column (str): Name of the column to index
        bin_number (int): Number of bins for the histogram
        output_dir (str): Directory to save figure to

    Returns:
        fig: The figure object the hisotgram was plotted on
        ax: The axis of the figure the histogram was plotted on

    """
    db = celldatabase.load_hdf(
        "/var/tmp/figuresdata/2019astrpi/direct_and_indirect_cells.h5")
    # dbTuned = db.query(studyparams.TUNING_FILTER)
    D1DB = db.query(studyparams.D1_CELLS)
    nD1DB = db.query(studyparams.nD1_CELLS)
    D1DB = D1DB.replace([np.inf, -np.inf], np.nan)
    nD1DB = nD1DB.replace([np.inf, -np.inf], np.nan)
    D1DB = D1DB[D1DB[data_column].notnull()]
    nD1DB = nD1DB[nD1DB[data_column].notnull()]
    D1Hist, D1bins = np.histogram(D1DB[data_column],
                                  bins=bin_number,
                                  density=True)
    nD1Hist, nD1bins = np.histogram(nD1DB[data_column],
                                    bins=bin_number,
                                    density=True)
    center = (D1bins[:-1] + D1bins[1:]) / 2
    width = 0.7 * (D1bins[1] - D1bins[0])
    D1Median = np.median(D1DB[data_column])
    nD1Median = np.median(nD1DB[data_column])

    fig = plt.gcf()
    fig.clf()
    figFilename = "{}".format(data_column)  # Do not include extension
    figFormat = 'png'  # 'pdf' or 'svg'
    figSize = [5, 5]

    ax = fig.add_subplot()
    ax.bar(center, D1Hist, width=width, align='center', label='D1', alpha=0.5)
    ax.bar(center,
           nD1Hist,
           width=width,
           align='center',
           label='nD1',
           alpha=0.5)
    ax.legend()
    ax.set_xlabel('{} value'.format(data_column))
    ax.set_ylabel('Frequency')
    ax.set_title(data_column)
    ymin, ymax = ax.get_ybound()
    ax.vlines(D1Median, ymin, ymax, color="Green")
    ax.vlines(nD1Median, ymin, ymax, color="Red")

    extraplots.save_figure(figFilename, figFormat, figSize, output_dir, 'w')
    plt.show()
    return fig, ax
Example #2
0
    cellsThisArea = brainAreaEachCell == brainArea
    absSpikeDifEachCellThisArea = absSpikeDifEachCell[:, cellsThisArea]
    maxDifBinEachCellThisArea = np.argmax(absSpikeDifEachCellThisArea, axis=0)
    cellReInd = np.argsort(maxDifBinEachCellThisArea)
    sortedAbsSpikeDifEachCellThisArea = absSpikeDifEachCellThisArea[:,
                                                                    cellReInd]
    sortedAbsSpikeDifEachCell[:,
                              cellsThisArea] = sortedAbsSpikeDifEachCellThisArea

    ax = plt.subplot(1, 2, indA + 1)
    ax.imshow(np.transpose(sortedAbsSpikeDifEachCellThisArea),
              origin='lower',
              cmap='viridis',
              interpolation='nearest')
    ax.set_xticks(range(numOfBins +
                        1)[::10])  #np.arange(len(timeBinEdges))[::10])
    ax.set_xticklabels(
        np.arange(timePeriodToPlot[0], timePeriodToPlot[1] + 0.01,
                  binWidth * 10))
    #xticklabels = ['{:.1f}'.format(x) for x in xticks]
    #ax.xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:g}"))
    #plt.yticks([150, 50], brainAreaLabels)
    ax.set_yticks([0, 50, 100])
    ax.set_ylabel('{}\nCell number'.format(brainArea))
    ax.set_xlabel('Time from movement onset (sec)')

if SAVE_FIGURE:
    extraplots.save_figure(figFilename, figFormat, figSize, outputDir)

plt.show()
Example #3
0
        ftraceEachTrial[cellInd1, trialsHighFreq]
    ]).T
    dataPoints = np.vstack([class0, class1])
    dataLabels = np.concatenate([np.zeros(nClass0), np.ones(nClass1)])
    clf = svm.SVC(kernel='linear', C=10)
    clf.fit(dataPoints, dataLabels)
    # -- Plot boundary --
    #plot_contours(ax0, clf, dataPoints, dataLabels)
    xlim = ax0.get_xlim()
    ylim = ax0.get_ylim()
    xx = np.linspace(xlim[0], xlim[1], 4)
    yy = np.linspace(ylim[0], ylim[1], 4)
    YY, XX = np.meshgrid(yy, xx)
    xy = np.vstack([XX.ravel(), YY.ravel()]).T
    Z = clf.decision_function(xy).reshape(XX.shape)
    colorBoundary = cp.TangoPalette['Chameleon2']
    #ax0.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,
    #            linestyles=['--', '-', '--'])
    hbound = ax0.contour(XX,
                         YY,
                         Z,
                         colors=colorBoundary,
                         levels=[0],
                         linestyles=['-'],
                         zorder=-1)

SAVEFIG = 0
if SAVEFIG:
    figname = 'twocell_scatter'
    extraplots.save_figure(figname, 'svg', [3.5, 3.5], outputDir='/tmp/')
Example #4
0
    plt.plot(xvals, schedData[featureToPlot], 'o', mfc='none', mec=pointsColor)
    thisMedian = dataMedian[featureToPlot][schedName]
    plt.bar(schedMapping[schedName],
            thisMedian,
            width=0.75,
            lw=2,
            fc=barFaceColor,
            ec=barEdgeColor)

#plt.ylabel(featureToPlot, fontsize=labelFontSize)
plt.ylabel('Performance (%)', fontsize=labelsFontSize)

ax0.set_xticks(np.arange(nSched))
ax0.set_xticklabels(schedSorted, fontsize=labelsFontSize)
if featureToPlot == 'Difference':
    plt.ylim([-20, 50])
else:
    plt.ylim([50, 100])
extraplots.boxoff(ax0)
extraplots.set_ticks_fontsize(ax0, ticksFontSize)

plt.show()

SAVEFIG = 1
if SAVEFIG:
    figname = 'behavior_effect_{}'.format(featureToPlot)
    extraplots.save_figure(figname,
                           'svg', [4.5, 3],
                           facecolor='w',
                           outputDir='/tmp/')
                                           xTickPeriod=1,
                                           xscale='linear')
    (plineL, pcapsL, pbarsL,
     pdotsL) = extraplots.plot_psychometric(1e-3 * possibleValuesL,
                                            fractionHitsEachValueL,
                                            ciHitsEachValueL,
                                            xTickPeriod=1,
                                            xscale='linear')

    plt.setp([pline, plineL], lw=3)
    plt.setp([plineL, pcapsL, pbarsL, pdotsL], color=laserColor)
    plt.setp(pdotsL, mfc=laserColor)
    #plt.setp([plineL,pcapsL,pbarsL,pdotsL],visible=False)
    #plt.setp([pline,pcaps,pbars,pdots],visible=False)

    plt.xlabel('Stimulus', fontsize=fontsize)
    plt.ylabel('Rightward trials (%)', fontsize=fontsize)
    extraplots.set_ticks_fontsize(plt.gca(), fontsize)

    plt.legend([pline, plineL], ['Control', 'Laser'], loc='lower right')
    plt.title(subject)
    plt.show()

sys.exit()
'''
extraplots.save_figure('/tmp/bili002_laser','pdf',[5,5],outputDir='/tmp/')
extraplots.save_figure('/tmp/bili002_control','pdf',[5,5],outputDir='/tmp/')
extraplots.save_figure('/tmp/bili006_laser','pdf',[5,5],outputDir='/tmp/')
extraplots.save_figure('/tmp/bili002_control','pdf',[5,5],outputDir='/tmp/')
'''
Example #6
0
extraplots.boxoff(plt.gca())
plt.xlabel('Time (s)', fontsize=fontSizeLabels)
plt.ylabel('Amplitude (V)', fontsize=fontSizeLabels)
extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks)
ax1.annotate('A', xy=(labelPosX[0],labelPosY[0]), xycoords='figure fraction',
             fontsize=fontSizePanel, fontweight='bold')

ax2 = plt.subplot(gs[1,:-1])
plt.plot(np.random.randn(20),np.random.randn(20),'o-',ms=markerSize,color='0.75',mfc=distanceColor,mec='w')
extraplots.boxoff(plt.gca())
extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks)
plt.xlabel('Time (s)', fontsize=fontSizeLabels)
plt.ylabel('Distance (m)', fontsize=fontSizeLabels)
ax2.annotate('B', xy=(labelPosX[0],labelPosY[1]), xycoords='figure fraction', fontsize=fontSizePanel, fontweight='bold')

ax3 = plt.subplot(gs[1:, -1])
plt.plot(np.random.randn(20),np.random.randn(20),'o-',ms=markerSize,color='0.75',mfc=velocityColor,mec='w')
extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks)
plt.xlabel('Time (s)', fontsize=fontSizeLabels)
plt.ylabel('Velocity (m/s)', fontsize=fontSizeLabels)
xLims = [-2,2]
ax3.set_xlim(xLims)
ax3.set_xticks(np.arange(xLims[0],xLims[1]+1))
ax3.annotate('C', xy=(labelPosX[1],labelPosY[1]), xycoords='figure fraction', fontsize=fontSizePanel, fontweight='bold')

plt.show()

if SAVE_FIGURE:
    extraplots.save_figure(figFilename, figFormat, figSize, outputDir)

ax2 = plt.subplot(gs[1, :-1])
plt.plot(np.random.randn(20), np.random.randn(20), 'o', mfc='none')
extraplots.boxoff(plt.gca())
extraplots.set_ticks_fontsize(plt.gca(), fontSizeTicks)
plt.xlabel('Time (s)', fontsize=fontSizeLabels)
plt.ylabel('Amplitude (V)', fontsize=fontSizeLabels)
ax2.annotate('B',
             xy=(labelPosX[0], labelPosY[1]),
             xycoords='figure fraction',
             fontsize=fontSizePanel,
             fontweight='bold')

ax3 = plt.subplot(gs[1:, -1])
plt.plot(np.random.randn(20), np.random.randn(20), 'o', mfc='none')
extraplots.set_ticks_fontsize(plt.gca(), fontSizeTicks)
plt.xlabel('Time (s)', fontsize=fontSizeLabels)
plt.ylabel('Amplitude (V)', fontsize=fontSizeLabels)
ax2.annotate('C',
             xy=(labelPosX[1], labelPosY[1]),
             xycoords='figure fraction',
             fontsize=fontSizePanel,
             fontweight='bold')

plt.show()

figFormat = 'pdf'  #'svg'
figFilename = 'testfig'  # Do not include extension
if PRINT_FIGURE:
    extraplots.save_figure(figFilename, figFormat, [8, 6], outputDir)
        for band in range(len(numBands)):
            bias = np.zeros(len(numLasers))
            for laser in range(len(numLasers)):
                trialsThisCond = trialsEachCond[:, laser, band]
                bias[laser] = 1.0 * (np.sum(toneChoice[trialsThisCond]) - np.sum(noiseChoice[trialsThisCond])) / \
                              (np.sum(toneChoice[trialsThisCond]) + np.sum(noiseChoice[trialsThisCond]))

            xVals = barLoc + xLocs[band]
            plt.plot(xVals, bias, 'k-', lw=2)
            l1, = plt.plot(xVals[0], bias[0], 'o', mec='k', mfc='k', ms=10)
            l2, = plt.plot(xVals[1], bias[1], 'o', mec='k', mfc='white', ms=10)

        axBias.legend([l1, l2], ['control', legendLabel[indType]])

        axBias.set_xlim(xLocs[0] - 0.5, xLocs[-1] + 0.5)
        axBias.set_xticks(xLocs)
        axBias.set_xticklabels(numBands)
        axBias.set_xlabel('Masker bandwidth (oct)')

        yLims = axBias.get_ylim()
        axBias.set_ylim(yLims[0] - 0.1, yLims[1] + 0.1)
        axBias.set_ylabel('Bias')

        extraplots.boxoff(axBias)

        plt.suptitle(mouse + ' ({})'.format(mouseLabel[indType]))

        figFilename = '{}_behav_report'.format(mouse)
        extraplots.save_figure(figFilename, 'png', [9, 4], '/tmp/')
    # tractFig = fig1
    # sliceNum = 207

    if tract['atlasZ']<zBound:
        tractAx = axs[0]
        tractFig = figs[0]
        sliceNum = 202
    elif (tract['atlasZ']>zBound):
        tractAx = axs[1]
        tractFig = figs[1]
        sliceNum = 209

    plt.sca(tractAx)
    plt.figure(tractFig.number)

    tractAx.imshow(np.rot90(atlas[:,:,sliceNum], -1), 'gray')
    plt.hold(1)
    # tractAx.plot([tract['tipCoords'][0], tract['brainSurfCoords'][0]], [tract['tipCoords'][1], tract['brainSurfCoords'][1]],
    #             color=lineColor, linewidth=lineWidth)
    print tract['brainSurfCoords']
    for coordPair in tract['siteCoords']:
        tractAx.plot(coordPair[0], coordPair[1], '.', mfc=markerColor, mec=markerColor, ms = 2)
    plt.hold(1)


for indFig, fig in enumerate(figs):
    plt.figure(fig.number)
    extraplots.save_figure('AC_tracts{}'.format(indFig+1), 'svg', (5, 3), outputDir=figDir)
# extraplots.save_figure('tractsAC', 'svg', (5, 3), outputDir='/tmp')
plt.show()
Example #10
0
        tractAx = axs[1]
        tractFig = figs[1]
        sliceNum = 193
    elif (tract['atlasZ'] > zBounds[1]):
        tractAx = axs[2]
        tractFig = figs[2]
        sliceNum = 206
    plt.sca(tractAx)
    plt.figure(tractFig.number)

    tractAx.imshow(np.rot90(atlas[:, :, sliceNum], -1), 'gray')
    plt.hold(1)
    tractAx.plot([tract['tipCoords'][0], tract['brainSurfCoords'][0]],
                 [tract['tipCoords'][1], tract['brainSurfCoords'][1]],
                 color=lineColor,
                 linewidth=lineWidth)
    for coordPair in tract['siteCoords']:
        tractAx.plot(coordPair[0],
                     coordPair[1],
                     '*',
                     mfc=markerColor,
                     mec=markerColor)
    plt.hold(1)

for indFig, fig in enumerate(figs):
    plt.figure(fig.number)
    extraplots.save_figure('tracts{}'.format(indFig + 1),
                           'svg', (5, 3),
                           outputDir='/tmp')
plt.show()
Example #11
0
ax2 = plt.subplot(gs[1,:-2])
trialsThisSecondVal = trialsEachCond[:, :, 1]
pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                indexLimitsEachTrial,
                                                timeRange = [-0.2, 1.5],
                                                trialsEachCond=trialsThisSecondVal,
                                                labels=firstSortLabels)
plt.setp(pRaster, ms=4)
extraplots.boxoff(plt.gca())
extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks)
plt.xlabel('Time from stimulus onset (s)', fontsize=fontSizeLabels)
plt.ylabel('Bandwidth (octaves)', fontsize=fontSizeLabels)
ax2.annotate('B', xy=(labelPosX[0],labelPosY[1]), xycoords='figure fraction', fontsize=fontSizePanel, fontweight='bold')


ax3 = plt.subplot(gs[0:, -2:])
spikeArray, errorArray, baseSpikeRate = bandwidths_analysis.band_select(spikeTimestamps, eventOnsetTimes, ampEachTrial, bandEachTrial, timeRange = [0,1])
bandwidths_analysis.band_select_plot(spikeArray, errorArray, baseSpikeRate, np.unique(bandEachTrial), legend = True, labels = ['54 dB', '66 dB'])
extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks)
plt.xlabel('Bandwidth (octaves)', fontsize=fontSizeLabels)
plt.ylabel('Average number of spikes during stimulus', fontsize=fontSizeLabels)
ax3.annotate('C', xy=(labelPosX[1],labelPosY[0]), xycoords='figure fraction', fontsize=fontSizePanel, fontweight='bold')

plt.show()

figFormat = 'pdf' #'svg' 
figFilename = 'testfig' # Do not include extension
if PRINT_FIGURE:
    extraplots.save_figure(figFilename, figFormat, [8,6], outputDir)
                               'o',
                               mec='k',
                               mfc='k',
                               ms=10)
                l2, = plt.plot(xVals[1],
                               threshold[1],
                               'o',
                               mec='k',
                               mfc='white',
                               ms=10)

        if all(threshold):
            axThresh.legend([l1, l2], ['control', legendLabel[indType]])

            axThresh.set_xlim(xLocs[0] - 0.5, xLocs[-1] + 0.5)
            axThresh.set_xticks(xLocs)
            axThresh.set_xticklabels(numBands)
            axThresh.set_xlabel('Masker bandwidth (oct)')

            yLims = axThresh.get_ylim()
            axThresh.set_ylim(yLims[0] - 10, yLims[1] + 10)
            axThresh.set_ylabel('Detection threshold (dB)')

            extraplots.boxoff(axThresh)

        plt.suptitle(mouse + ' ({})'.format(mouseLabel[indType]))

        figFilename = '{}_logistic_fit_report'.format(mouse)
        extraplots.save_figure(figFilename, 'png', [3 * len(numBands) + 2, 4],
                               '/tmp/')
    exampleCells.append(cell)

    if CASE==0:
        if len(sys.argv)>1:
            cellInd = int(sys.argv[1])
        else:
            print "Use sys.argv to select a cell. Defaulting to cell 0"
            cellInd = 0

        cellDict = exampleCells[cellInd]
        cell = find_cell(db, cellDict['subject'], cellDict['date'], cellDict['depth'], cellDict['tetrode'], cellDict['cluster']).iloc[0]
        am_example(cell)
        plt.show()
        figFilename = 'exampleAM_{}'.format(cellInd)
        print 'Saving {}'.format(figFilename)
        extraplots.save_figure(figFilename, 'svg', [6,10], '/tmp/')
        

    if CASE==1:
        #Rsync all the example data
        for cellDict in exampleCells:
            cell = find_cell(db, cellDict['subject'], cellDict['date'], cellDict['depth'], cellDict['tetrode'], cellDict['cluster']).iloc[0]
            amInd = celldatabase.get_session_inds(cell, 'am')[0]
            amSession = cell['ephys'][amInd]
            rsync_session_data(cell['subject'], amSession)
            rsync_session_data(cell['subject'], '{}_kk'.format(amSession))
            amBehav = cell['behavior'][amInd]
            rsync_behavior(cell['subject'], amBehav)

    if CASE==2:
        ### THIS IS FOR PLOTTING ALL CELLS BY THEIR MAX SYNC FREQ
    ax = plt.subplot2grid((2, len(allSessions)), (1, indSession))
    chordEstimates[
        indSession, :] = behavioranalysis.plot_psycurve_fit_and_data(
            theseDataObjs[1], thisColor)
    ax.tick_params(axis='both', which='major', labelsize=labelFontSize)
    ax.tick_params(axis='both', which='minor', labelsize=labelFontSize)
    # plt.title('{}'.format([key for key, value in theseSoundTypes.iteritems()][1]))
    behavioranalysis.nice_psycurve_settings(ax,
                                            fontsize=10,
                                            lineweight=2,
                                            fitlineinds=[0])
    if indSession > 0:
        ax.set_ylabel('')
    else:
        ax.set_ylabel('Chords\nFraction rightward trials')

figSize = [30, 6]

# figtext(0.075, 0.7, 'Fraction of trials going to the right', rotation='vertical')
# figtext(0.4, 0.05, 'Log2(frequency) - octaves')
plt.suptitle(animal)
plt.gcf().set_facecolor('w')
outputDir = '/home/nick/data/dissertation_amod'
extraplots.save_figure('{}_muscimol_inactivation_daily'.format(animal),
                       'png',
                       figSize,
                       outputDir=outputDir)

plt.show()