def plot_bars(ax, dataMat, label):
    for indSubject, subject in enumerate(subjects):
        for indCond, condition in enumerate(conditions):
            sessionsThisCondThisSubject = dataMat[indSubject, :, indCond]
            ax.plot(np.zeros(len(sessionsThisCondThisSubject)) + (indSubject + 0.5*width + indCond*width) + pointShift,
                    sessionsThisCondThisSubject, marker='o', linestyle='none', mec=condColors[indCond], mfc='none')
            ax.hold(1)

    rects1 = ax.bar(ind, dataMat[:, :, 0].mean(1)-0.5, width, bottom=0.5, edgecolor='k', facecolor='w', lw=2, label='Saline')
    rects2 = ax.bar(ind+width+0.015, dataMat[:, :, 1].mean(1)-0.5, width, bottom=0.5, edgecolor=muscimolColor, lw=2, facecolor='w', label='Muscimol')

    ax.set_xticks(ind + width)
    ax.set_xticklabels(np.arange(6)+1, fontsize=fontSizeLabels)
    ax.set_xlabel('Mouse', fontsize=fontSizeLabels)
    ax.axhline(y=0.5, color='0.5', linestyle='-')
    # ax.set_ylim([0.45, 1])
    ax.set_xlim([ind[0]-0.5*width, ind[-1]+2.5*width ])
    ax.set_ylabel('Number of trials', fontsize=fontSizeLabels)
    # ax.set_yticks([0.5, 1])

    extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks)
    extraplots.boxoff(ax)

    ax.legend(bbox_to_anchor=(0.95, 0.6),
            loc=3,
            numpoints=1,
            fontsize=fontSizeLabels,
            ncol=1,
            columnspacing=1.5,
            frameon=False)

    for i in [1, 3, 4]:
        extraplots.significance_stars([i+0.5*width,i+1.5*width], 1000, 50, starSize=6, gapFactor=0.4, color='0.5')
Ejemplo n.º 2
0
def nice_psycurve_settings(ax, fitcolor=None, fontsize=20, lineweight=3, fitlineinds=[3]):

    '''
    A hack for setting some psycurve axes properties, especially the weight of the line and the xticks
    I made this because I am using the fxn plot_psycurve_fit_and_data, which obscures handles to things
    that I later need (like the lines, etc. ) This function will be useless if I make plots in a better way. 

    '''

    extraplots.boxoff(ax)
    extraplots.set_ticks_fontsize(ax, fontsize)


    for lineind in fitlineinds:
        fitline = ax.lines[lineind]
        plt.setp(fitline, lw=lineweight)

    if fitcolor:
        plt.setp(fitline, color=fitcolor)

    xticklabels = [item.get_text() for item in ax.get_xticklabels()]
    xticks = ax.get_xticks()
    newXtickLabels = np.logspace(xticks[0], xticks[-1], 3, base=2)

    ax.set_xticks(np.log2(np.array(newXtickLabels)))
    if min(newXtickLabels) > 1000:
        ax.set_xticklabels(['{:.3}'.format(x/1000.0) for x in newXtickLabels])
    else:
        ax.set_xticklabels(['{:.3}'.format(x) for x in newXtickLabels])
Ejemplo n.º 3
0
    def plot_raster_and_PSTH(sessiontype, gs, color='k'):
        axRaster = plt.subplot(gs[0])
        ephysData, bdata = cell.load(sessiontype)
        eventOnsetTimes = ephysData['events']['stimOn']
        eventOnsetTimes = spikesanalysis.minimum_event_onset_diff(
            eventOnsetTimes, minEventOnsetDiff=0.5)
        timeRange = [-0.3, 1.0]
        (spikeTimesFromEventOnset, trialIndexForEachSpike,
         indexLimitsEachTrial) = spikesanalysis.eventlocked_spiketimes(
             ephysData['spikeTimes'], eventOnsetTimes, timeRange)
        # pRaster, hCond, zLine = extraplots.raster_plot(spikeTimesFromEventOnset,
        #                                                 indexLimitsEachTrial,
        #                                                 timeRange)
        axRaster.plot(spikeTimesFromEventOnset,
                      trialIndexForEachSpike,
                      'k.',
                      ms=1,
                      rasterized=True)
        # plt.setp(pRaster, ms=1)
        axRaster.set_xlim(timeRange)
        axRaster.set_xticks([])
        # axRaster.axis('off')
        extraplots.boxoff(axRaster)
        axRaster.set_yticks([len(eventOnsetTimes)])

        axPSTH = plt.subplot(gs[1])
        smoothPSTH = True
        psthLineWidth = 2
        smoothWinSize = 1
        binsize = 10  #in milliseconds
        binEdges = np.around(np.arange(timeRange[0] - (binsize / 1000.0),
                                       timeRange[1] + 2 * (binsize / 1000.0),
                                       (binsize / 1000.0)),
                             decimals=2)
        winShape = np.concatenate((np.zeros(smoothWinSize),
                                   np.ones(smoothWinSize)))  # Square (causal)
        winShape = winShape / np.sum(winShape)
        psthTimeBase = np.linspace(timeRange[0],
                                   timeRange[1],
                                   num=len(binEdges) - 1)

        spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
            spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)

        thisPSTH = np.mean(spikeCountMat, axis=0)
        if smoothPSTH:
            thisPSTH = np.convolve(thisPSTH, winShape, mode='same')
        ratePSTH = thisPSTH / float(binsize / 1000.0)
        axPSTH.plot(psthTimeBase, ratePSTH, '-', color=color, lw=psthLineWidth)

        displayRange = timeRange
        axPSTH.set_xlim(displayRange)
        extraplots.boxoff(axPSTH)
        axPSTH.set_ylim([0, max(ratePSTH)])
        axPSTH.set_yticks([0, np.floor(np.max(ratePSTH))])
        # axPSTH.set_ylabel('spk/s', fontsize=fontSizeLabels)
        axPSTH.set_ylabel('spk/s')
def plot_bars(ax, dataMat, label):
    for indSubject, subject in enumerate(subjects):
        for indCond, condition in enumerate(conditions):
            sessionsThisCondThisSubject = dataMat[indSubject, :, indCond]
            ax.plot(np.zeros(len(sessionsThisCondThisSubject)) +
                    (indSubject + 0.5 * width + indCond * width) + pointShift,
                    sessionsThisCondThisSubject,
                    marker='o',
                    linestyle='none',
                    mec=condColors[indCond],
                    mfc='none')
            ax.hold(1)

    rects1 = ax.bar(ind,
                    dataMat[:, :, 0].mean(1) - 0.5,
                    width,
                    bottom=0.5,
                    edgecolor='k',
                    facecolor='w',
                    lw=2,
                    label='Saline')
    rects2 = ax.bar(ind + width + 0.015,
                    dataMat[:, :, 1].mean(1) - 0.5,
                    width,
                    bottom=0.5,
                    edgecolor=muscimolColor,
                    lw=2,
                    facecolor='w',
                    label='Muscimol')

    ax.set_xticks(ind + width)
    ax.set_xticklabels(np.arange(6) + 1, fontsize=fontSizeLabels)
    ax.set_xlabel('Mouse', fontsize=fontSizeLabels)
    ax.axhline(y=0.5, color='0.5', linestyle='-')
    # ax.set_ylim([0.45, 1])
    ax.set_xlim([ind[0] - 0.5 * width, ind[-1] + 2.5 * width])
    ax.set_ylabel('Number of trials', fontsize=fontSizeLabels)
    # ax.set_yticks([0.5, 1])

    extraplots.set_ticks_fontsize(plt.gca(), fontSizeTicks)
    extraplots.boxoff(ax)

    ax.legend(bbox_to_anchor=(0.95, 0.6),
              loc=3,
              numpoints=1,
              fontsize=fontSizeLabels,
              ncol=1,
              columnspacing=1.5,
              frameon=False)

    for i in [1, 3, 4]:
        extraplots.significance_stars([i + 0.5 * width, i + 1.5 * width],
                                      1000,
                                      50,
                                      starSize=6,
                                      gapFactor=0.4,
                                      color='0.5')
Ejemplo n.º 5
0
def plot_hist(ax, dataArr, color, label):
    lowFreq = 4
    highFreq = 128
    nFreqs = 11
    freqs = np.logspace(np.log10(lowFreq), np.log10(highFreq), nFreqs)
    freqs = np.round(freqs, decimals=1)
    freqs = np.r_[0, freqs]
    freqLabels = ['{}'.format(freq) for freq in freqs[1:]]
    freqLabels = ['NS', ' '] + freqLabels

    roundData = np.round(dataArr[pd.notnull(dataArr)], decimals=1)
    counts = Counter(roundData)

    freqsToPlot = np.r_[0, 1, freqs[1:]]
    index = np.arange(len(freqsToPlot))

    heights = []
    for freq in freqsToPlot:
        try:
            heights.append(100 * counts[freq] / np.double(len(roundData)))
        except KeyError:
            heights.append(0)

    barWidth = 0.8
    rects = plt.bar(index + 0.5 * barWidth,
                    heights,
                    barWidth,
                    label=label,
                    color=color)
    plt.xticks(index + barWidth, freqs)
    ax.set_xticklabels(freqLabels, rotation='vertical')
    plt.ylabel('% cells')
    # ax.set_xlim([1.5,index[-1]+2*barWidth-0.5])
    # plt.xlabel('Highest AM rate to which\ncell can synchronize (Hz)')
    extraplots.boxoff(ax)

    height = max(heights) * 0.05
    extraplots.breakaxis(1.8, 0, 0.3, height, gap=0.4)
    ax.tick_params(axis='x', length=0)
    plt.ylim([0, max(heights) + 1])
    labelText = '{}, N={}'.format(label, len(roundData))
    ax.annotate(labelText,
                xy=(0.1, 0.9),
                xycoords='axes fraction',
                fontsize=9,
                fontweight='bold')
    return rects
def plot_band_psychometric(validPerSNR, rightPerSNR, possibleSNRs, colour = 'k', linestyle='-', xlabel=True, ylabel=True):
    from statsmodels.stats.proportion import proportion_confint
    performance = []
    upper = []
    lower = []
    for inds in range(len(possibleSNRs)):
        CIthisSNR = np.array(proportion_confint(rightPerSNR[inds], validPerSNR[inds], method = 'wilson'))
        performance.append(100.0*rightPerSNR[inds]/validPerSNR[inds])
        upper.append(100.0*CIthisSNR[1]-performance[-1])
        lower.append(performance[-1]-100.0*CIthisSNR[0])
    plt.plot(np.arange(len(possibleSNRs)), performance, linestyle, marker='o', color=colour, mec=colour, lw=3, ms=10)
    plt.errorbar(np.arange(len(possibleSNRs)), performance, yerr = [lower, upper], color=colour, lw=2, ls=linestyle)
    if ylabel:
        plt.ylabel("% rightward", fontsize=16)
    if xlabel:
        plt.xlabel('SNR (dB)', fontsize=16)
    plt.xticks(np.arange(len(possibleSNRs)), possibleSNRs)
    plt.ylim((0,100))
    ax = plt.gca()
    extraplots.boxoff(ax)
Ejemplo n.º 7
0
def plot_events_in_time(timeStamps,nBins=50,fontsize=8):
    '''
    Plot histogram of inter-spike interval (in msec, log scale)

    Parameters
    ----------
    timeStamps : array (float in sec)
    '''
    ax = plt.gca()
    timeBinEdges = np.linspace(timeStamps[0],timeStamps[-1],nBins) # in microsec
    # FIXME: Limits depend on the time of the first spike (not of recording)
    (nEvents,binEdges) = np.histogram(timeStamps,bins=timeBinEdges)
    hp, = plt.plot((binEdges-timeStamps[0])/60.0, np.r_[nEvents,0], drawstyle='steps-post')
    plt.setp(hp,lw=1,color='k')
    plt.xlabel('Time (min)')
    plt.axis('tight')
    ax.set_yticks(plt.ylim())
    extraplots.boxoff(ax)
    extraplots.set_ticks_fontsize(ax,fontsize)
    return hp
Ejemplo n.º 8
0
def multisession_events_in_time(timeStamps, nBins=50, fontsize=8):
    '''
    Plot the spike timestamps throughout the recording session.

    IF the acquisition system is restarted at a site, then the timestamps will
    also reset and cause a failure in the traditional implementation of this method
    (spikesorting.plot_events_in_time). This method finds any negative ISIs (which mark
    the spot where the timestamps were reset), adds the value of the ts immediatly before
    the reset to all remaining timestamps, and plots a red line at this time point to indicate
    that there is an uncertain amount of time between the spikes before and after this point. 

    TODO: Still need to implement the fix I described above and then use the method in the
    multisession report

    Parameters
    ----------
    timeStamps : array (float in sec)
    '''

    # ISI = np.diff(timeStamps)
    # if np.any(ISI<0):

    ax = plt.gca()
    timeBinEdges = np.linspace(timeStamps[0], timeStamps[-1],
                               nBins)  # in microsec
    # FIXME: Limits depend on the time of the first spike (not of recording)
    (nEvents, binEdges) = np.histogram(timeStamps, bins=timeBinEdges)
    hp, = plt.plot((binEdges - timeStamps[0]) / 60.0,
                   np.r_[nEvents, 0],
                   drawstyle='steps-post')
    plt.setp(hp, lw=1, color='k')
    plt.xlabel('Time (min)')
    plt.axis('tight')
    ax.set_yticks(plt.ylim())
    extraplots.boxoff(ax)
    extraplots.set_ticks_fontsize(ax, fontsize)
    return hp
Ejemplo n.º 9
0
                       color=colorNoise,
                       clip_on=False)

spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
    spikeTimesFromEventOnset, indexLimitsEachTrial, binEdges)
thisPSTH = np.mean(spikeCountMat, axis=0)
if smoothPSTH:
    thisPSTH = np.convolve(thisPSTH, winShape, mode='same')
ratePSTH = thisPSTH / float(binsize / 1000.0)
axThalNoisePSTH.plot(psthTimeBase,
                     ratePSTH,
                     '-',
                     color=colorPSTH,
                     lw=psthLineWidth)
axThalNoisePSTH.set_xlim(displayRange)
extraplots.boxoff(axThalNoisePSTH)
axThalNoisePSTH.set_ylim([0, max(ratePSTH)])
axThalNoisePSTH.set_yticks([0, np.floor(np.max(ratePSTH))])
axThalNoisePSTH.set_ylabel('spk/s', fontsize=fontSizeLabels)
axThalNoisePSTH.set_xticks([0, 0.3])
extraplots.set_ticks_fontsize(axThalNoisePSTH, fontSizeTicks)

## -- Thalamus Laser -- ##
spikeTimesFromEventOnset = None
trialIndexForEachSpike = None
indexLimitsEachTrial = None
sessiontype = 'laserpulse'
cell = ephyscore.Cell(rowThal)
ephysData, bdata = cell.load(sessiontype)
spikeTimes = ephysData['spikeTimes']
eventOnsetTimes = ephysData['events']['stimOn']
Ejemplo n.º 10
0
         ftraceEachTrial[cellInd1, trialsHighFreq],
         'o',
         ms=markerSize,
         mew=3,
         mec=color1,
         mfc='none',
         rasterized=RASTERIZED)

#plt.axis('square')
#plt.xlim()
#plt.ylim()
plt.axis([4866, 6238, 4407, 7830])
ax0.set_xticklabels([])
ax0.set_yticklabels([])
ax0.tick_params('both', direction='in')
extraplots.boxoff(ax0)

fontSize = 18
plt.xlabel('Response: Neuron {}'.format(cellsToPlot[0]), fontsize=fontSize)
plt.ylabel('Response: Neuron {}'.format(cellsToPlot[1]), fontsize=fontSize)
plt.show()

# -- Classifier --
if 1:
    from sklearn import svm
    nClass0 = np.sum(trialsLowFreq)
    nClass1 = np.sum(trialsHighFreq)
    class0 = np.vstack([
        ftraceEachTrial[cellInd0, trialsLowFreq],
        ftraceEachTrial[cellInd1, trialsLowFreq]
    ]).T
                 edgecolor='k',
                 facecolor='w')
rects2 = ax2.bar(ind + width + 0.015,
                 dataMat[:, :, 1].mean(1) - 0.5,
                 width,
                 bottom=0.5,
                 edgecolor='r',
                 facecolor='w')

ax2.set_xticks(ind + width)
ax2.set_xticklabels(np.arange(6) + 1, fontsize=fontSizeLabels)
ax2.set_xlabel('Mouse', fontsize=fontSizeLabels)
ax2.axhline(y=0.5, color='0.5', linestyle='-')
# ax2.set_ylim([0.45, 1])
ax2.set_xlim([ind[0] - 0.5 * width, ind[-1] + 2.5 * width])
ax2.set_ylabel('Number of Trials', fontsize=fontSizeLabels)
# ax2.set_yticks([0.5, 1])

extraplots.set_ticks_fontsize(plt.gca(), fontSizeTicks)
extraplots.boxoff(ax2)
# ax2.annotate('C', xy=(labelPosX[0],labelPosY[0]), xycoords='axes fraction', fontsize=fontSizePanel, fontweight='bold')

plt.show()

for indSubject in range(5):
    subDataSal = dataMat[indSubject, :, 0]
    subDataMus = dataMat[indSubject, :, 1]

    print indSubject
    print stats.ranksums(subDataSal, subDataMus)
def plot_ave_psycurve_reward_change(animal, sessions):
    FREQCOLORS = [
        '0.3', colorpalette.TangoPalette['Orange2'],
        colorpalette.TangoPalette['SkyBlue2']
    ]

    allBehavDataThisAnimal = behavioranalysis.load_many_sessions(
        animal, sessions)
    targetFrequency = allBehavDataThisAnimal['targetFrequency']
    choice = allBehavDataThisAnimal['choice']
    valid = allBehavDataThisAnimal['valid'] & (
        choice != allBehavDataThisAnimal.labels['choice']['none'])
    choiceRight = choice == allBehavDataThisAnimal.labels['choice']['right']
    currentBlock = allBehavDataThisAnimal['currentBlock']
    blockTypes = [
        allBehavDataThisAnimal.labels['currentBlock']['same_reward'],
        allBehavDataThisAnimal.labels['currentBlock']['more_left'],
        allBehavDataThisAnimal.labels['currentBlock']['more_right']
    ]
    #blockTypes = [allBehavDataThisAnimal.labels['currentBlock']['more_left'],allBehavDataThisAnimal.labels['currentBlock']['more_right']]
    blockLabels = ['same_reward', 'more_left', 'more_right']
    #blockLabels = ['more_left','more_right']
    trialsEachType = behavioranalysis.find_trials_each_type(
        currentBlock, blockTypes)

    nFreqs = len(np.unique(targetFrequency))
    #print trialsEachType
    nBlocks = len(blockTypes)
    #thisAnimalPos = inda
    #ax1=plt.subplot(gs[thisAnimalPos])
    #plt.clf()
    fontsize = 12
    allPline = []
    blockLegends = []
    fractionHitsEachValueAllBlocks = np.empty((nBlocks, nFreqs))

    for blockType in range(nBlocks):
        if np.any(trialsEachType[:, blockType]):
            targetFrequencyThisBlock = targetFrequency[
                trialsEachType[:, blockType]]
            validThisBlock = valid[trialsEachType[:, blockType]]
            choiceRightThisBlock = choiceRight[trialsEachType[:, blockType]]
            #currentBlockValue = currentBlock[trialsEachBlock[0,block]]
            (possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
            behavioranalysis.calculate_psychometric(choiceRightThisBlock,targetFrequencyThisBlock,validThisBlock)

            logPossibleValues = np.log2(possibleValues)
            lowerFreqConstraint = logPossibleValues[1]
            upperFreqConstraint = logPossibleValues[-2]
            maxFreq = max(logPossibleValues)
            minFreq = min(logPossibleValues)

            constraints = ('Uniform({}, {})'.format(lowerFreqConstraint,
                                                    upperFreqConstraint),
                           'Uniform(0,5)', 'Uniform(0,1)', 'Uniform(0,1)')
            estimate = extrastats.psychometric_fit(logPossibleValues,
                                                   nTrialsEachValue,
                                                   nHitsEachValue, constraints)

            fractionHitsEachValueAllBlocks[
                blockType, :] = fractionHitsEachValue

            upperWhisker = ciHitsEachValue[1, :] - fractionHitsEachValue
            lowerWhisker = fractionHitsEachValue - ciHitsEachValue[0, :]

            xRange = logPossibleValues[-1] - logPossibleValues[1]
            fitxvals = np.linspace(logPossibleValues[0] - 0.1 * xRange,
                                   logPossibleValues[-1] + 0.1 * xRange, 40)
            fityvals = extrastats.psychfun(fitxvals, *estimate)

            # (pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(1e-3*possibleValues,fractionHitsEachValue,  ciHitsEachValue,xTickPeriod=1)

            ax = plt.gca()
            ax.hold(True)
            (pline, pcaps, pbars) = ax.errorbar(
                logPossibleValues,
                100 * fractionHitsEachValue,
                yerr=[100 * lowerWhisker, 100 * upperWhisker],
                ecolor=FREQCOLORS[blockType],
                fmt=None,
                clip_on=False)

            pdots = ax.plot(logPossibleValues,
                            100 * fractionHitsEachValue,
                            'o',
                            ms=6,
                            mec='None',
                            mfc=FREQCOLORS[blockType],
                            clip_on=False)
            if blockType == 0:
                pfit = ax.plot(fitxvals,
                               100 * fityvals,
                               color=FREQCOLORS[blockType],
                               lw=2,
                               clip_on=False,
                               linestyle='--')
            else:
                pfit = ax.plot(fitxvals,
                               100 * fityvals,
                               color=FREQCOLORS[blockType],
                               lw=2,
                               clip_on=False)

            # plt.setp((pline, pcaps, pbars), color=FREQCOLORS[blockType])
            # plt.setp((pline, pbars), color=FREQCOLORS[blockType])
            # plt.setp(pdots, mfc=FREQCOLORS[blockType], mec=FREQCOLORS[blockType])
            allPline.append(pline)
            blockLegends.append(blockLabels[blockType])

            if blockType == nBlocks - 1:
                plt.xlabel('Frequency (kHz)', fontsize=fontsize)
                plt.ylabel('Rightward trials (%)', fontsize=fontsize)
                extraplots.set_ticks_fontsize(plt.gca(), fontsize)
                ax.set_xticks(logPossibleValues)
                tickLabels = [''] * len(possibleValues)
                tickLabels[0] = 6.2
                tickLabels[-1] = 19.2
                ax.set_xticklabels(tickLabels)
                ax.axhline(y=50, linestyle='-', color='0.7')
                extraplots.boxoff(ax)
                # legend = plt.legend(allPline,blockLegends,loc=2) #Add the legend manually to the current Axes.
                # ax = plt.gca().add_artist(legend)
                #plt.hold(True)
        #plt.legend(bbox_to_anchor=(1, 1), bbox_transform=plt.gcf().transFigure)
        #plt.show()
    # plt.title('%s %s-%s'%(animal,sessions[0],sessions[-1]))
    return fractionHitsEachValueAllBlocks
Ejemplo n.º 13
0
        bandIndexLimitsEachTrial = cell['indexLimitsEachTrial']
        rasterTimeRange = cell['rasterTimeRange']
        trialsEachCond = cell['trialsEachCond']
        trialsEachCond = trialsEachCond[:,1:] #don't include pure tone
        trialsEachCond = trialsEachCond[:-70,:] #remove last couple of trials where baseline seems to increase
        possibleBands = cell['possibleBands']
        possibleBands = possibleBands[1:]
        bandLabels = possibleBands.tolist()
        bandLabels[-1] = 'WN'
        colorEachCond = colours[indCell]*(len(possibleBands)/2+1)
        pRaster, hcond, zline = extraplots.raster_plot(bandSpikeTimesFromEventOnset,bandIndexLimitsEachTrial,rasterTimeRange,
                                                       trialsEachCond=trialsEachCond,labels=bandLabels,colorEachCond=colorEachCond)
        axRaster.annotate(panelLabels[indCell], xy=(labelPosX[1],labelPosY[indCell]), xycoords='figure fraction',
                         fontsize=fontSizePanel, fontweight='bold')
        plt.setp(pRaster, ms=3, color='k')
        extraplots.boxoff(axRaster)
        if indCell != 2:
            axRaster.set_xticklabels('')
        plt.ylabel('Bandwidth (oct)',fontsize=fontSizeLabels)
        
        yLims = np.array(plt.ylim())
        rect = patches.Rectangle((0.0,yLims[1]*1.02),1.0,yLims[1]*0.04,linewidth=1,edgecolor=soundColor,facecolor=soundColor,clip_on=False)
        axRaster.add_patch(rect)
        
    
    extraplots.set_ticks_fontsize(plt.gca(),fontSizeTicks)
    plt.xlabel('Time from sound onset (s)',fontsize=fontSizeLabels)



# -- Plots of sustained bandwidth tuning --
Ejemplo n.º 14
0
def plot_example_with_rate(subplotSpec, exampleName, color='k'):
    fig = plt.gcf()

    gs = gridspec.GridSpecFromSubplotSpec(1,
                                          4,
                                          subplot_spec=subplotSpec,
                                          wspace=-0.45,
                                          hspace=0.0)

    specRaster = gs[0:2]
    axRaster = plt.Subplot(fig, specRaster)
    fig.add_subplot(axRaster)

    spikeTimes = exampleSpikeTimes[exampleName]
    indexLimitsEachTrial = exampleIndexLimitsEachTrial[exampleName]
    timeRange = [-0.2, 0.7]
    freqEachTrial = exampleFreqEachTrial[exampleName]
    possibleFreq = np.unique(freqEachTrial)
    freqLabels = ['{0:.1f}'.format(freq) for freq in possibleFreq]
    trialsEachCondition = behavioranalysis.find_trials_each_type(
        freqEachTrial, possibleFreq)
    pRaster, hCond, zline = extraplots.raster_plot(spikeTimes,
                                                   indexLimitsEachTrial,
                                                   timeRange,
                                                   trialsEachCondition,
                                                   labels=freqLabels)
    plt.setp(pRaster, ms=2)
    ax = plt.gca()
    ax.set_xticks([0, 0.5])
    ax.set_xlabel('Time from sound onset (s)')
    ax.set_ylabel('AM Rate (Hz)')

    # ax.annotate('A', xy=(labelPosX[0],labelPosY[0]), xycoords='figure fraction',
    #             fontsize=fontSizePanel, fontweight='bold')

    countRange = [0.1, 0.5]
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimes, indexLimitsEachTrial, countRange)
    numSpikesInTimeRangeEachTrial = np.squeeze(spikeCountMat)

    numSpikesInTimeRangeEachTrial = np.squeeze(
        np.diff(indexLimitsEachTrial, axis=0))

    if len(numSpikesInTimeRangeEachTrial) == len(freqEachTrial) + 1:
        numSpikesInTimeRangeEachTrial = numSpikesInTimeRangeEachTrial[:-1]
    conditionMatShape = np.shape(trialsEachCondition)
    numRepeats = np.product(conditionMatShape[1:])
    nSpikesMat = np.reshape(numSpikesInTimeRangeEachTrial.repeat(numRepeats),
                            conditionMatShape)
    spikesFilteredByTrialType = nSpikesMat * trialsEachCondition
    avgSpikesArray = np.sum(spikesFilteredByTrialType, 0) / np.sum(
        trialsEachCondition, 0).astype('float') / np.diff(np.array(countRange))
    stdSpikesArray = np.std(spikesFilteredByTrialType, 0) / np.diff(
        np.array(countRange))

    specRate = gs[3]
    axRate = plt.Subplot(fig, specRate)
    fig.add_subplot(axRate)

    nRates = len(possibleFreq)
    plt.hold(True)
    plt.plot(avgSpikesArray,
             range(nRates),
             'ro-',
             mec='none',
             ms=7,
             lw=3,
             color=color)
    plt.plot(avgSpikesArray - stdSpikesArray, range(len(possibleFreq)), 'k:')
    plt.plot(avgSpikesArray + stdSpikesArray, range(len(possibleFreq)), 'k:')
    axRate.set_ylim([-0.5, nRates - 0.5])
    axRate.set_yticks(range(nRates))
    axRate.set_yticklabels([])

    #ax = plt.gca()
    axRate.set_xlabel('Firing rate (spk/s)')
    extraplots.boxoff(axRate)
    # extraplots.boxoff(ax, keep='right')
    return (axRaster, axRate)
Ejemplo n.º 15
0
        markerThisCond = markerEachCond[indc]
        for indSubject, oneSubject in enumerate(subjectsThisCond):
            sessionsThisSubject = sessionsThisCond & (subject==oneSubject)
            samples = (180/np.pi) * np.concatenate(deltaHeadAngle[sessionsThisSubject])# From radians to degrees
            samples = samples[:maxSamplesToInclude]
            xvals = np.tile(xPos[indc]+0.1*indSubject-0.1,len(samples))
            plt.plot(xvals,samples,'o',marker=markerEachSubject[indSubject],mfc='none',mec='0.75', zorder=-1,clip_on=False)
            meanVal = np.mean(samples)
            seVal = np.std(samples)/np.sqrt(len(samples))
            meanEachCondEachSubject[indc].append(meanVal)
            subjectIndFromAll = list(possibleSubjects).index(oneSubject)
            #print samples
            dataEachCondEachSubject[subjectIndFromAll][indc] = samples
            #[pline,pcap,pbar] = plt.errorbar(xPos[indc]+0.1*indSubject-0.2, meanVal, seVal, color=colorThisCond)
            pmark = plt.plot(xPos[indc]+0.1*indSubject-0.1, meanVal,markerThisCond,mfc=colorThisCond,mec='None')
    extraplots.boxoff(ax3)
    plt.ylabel('Change in angle (deg)')
    ax3.set_yticks(np.arange(-200,300,100))
    #plt.ylim([-200,200])
    plt.ylim(300*np.array([-1,1]))
    plt.xlim([-0.7,4.1])
    ax3.axes.get_xaxis().set_visible(False)
    ax3.spines['bottom'].set_visible(False)
    signifYpos = 300 #220
    extraplots.significance_stars([xPos[0],xPos[1]], signifYpos, 20, starSize=10, gapFactor=0.2, color='0.5')
    extraplots.significance_stars([xPos[2],xPos[3]], signifYpos, 20, starSize=10, gapFactor=0.2, color='0.5')
    plt.text(np.mean(xPos[0:2]), -signifYpos, 'Left', ha='center', fontsize=fontSizeLabels+2)
    plt.text(np.mean(xPos[2:4]), -signifYpos, 'Right', ha='center', fontsize=fontSizeLabels+2)
    plt.show()

    
Ejemplo n.º 16
0
    axLatency.plot(pos,
                   D1PopStat * 1000,
                   'o',
                   mec=colorD1,
                   mfc='None',
                   alpha=markerAlpha)
    medline(axLatency, np.median(D1PopStat) * 1000, 1, 0.5)
    axLatency.set_ylabel('Latency (ms)', fontsize=fontSizeTicks)
    # tickLabels = ['ATh:Str', 'AC:Str']
    tickLabels = [
        'nD1:Str\nn={}'.format(len(nD1PopStat)),
        'D1:Str\nn={}'.format(len(D1PopStat))
    ]
    axLatency.set_xticks(range(2))
    axLatency.set_xlim([-0.5, 1.5])
    extraplots.boxoff(axLatency)
    axLatency.set_ylim([-0.001, 65])

    extraplots.set_ticks_fontsize(axLatency, fontSizeTicks)
    axLatency.set_xticklabels(tickLabels, fontsize=fontSizeLabels, rotation=45)

    zstat, pVal = stats.ranksums(nD1PopStat, D1PopStat)

    # print "Ranksums test between thalamus and AC population stat ({}) vals: p={}".format(popStatCol, pVal) Remove Matt
    messages.append("{} p={}".format(popStatCol, pVal))
    '''
    if pVal<0.05:
        starMarker='*'
    else:
        starMarker='n.s.'
    extraplots.new_significance_stars([0, 1], yStars, yStarHeight, starMarker=starMarker,
Ejemplo n.º 17
0
	#Is this the correct thing to get to calculate psychometrics?
	choiceRight = choice==bdata.labels['choice']['right']
	targetFreq = bdata['targetFrequency']

	noLaserTrials = valid&(bdata['trialType']==0)

	(possibleValues,fractionHitsEachValue,ciHitsEachValue,nTrialsEachValue,nHitsEachValue)=\
	behavioranalysis.calculate_psychometric(choiceRight, targetFreq, noLaserTrials)

	(pline, pcaps, pbars, pdots) = extraplots.plot_psychometric(1e-3*possibleValues,fractionHitsEachValue,ciHitsEachValue,xTickPeriod=1)

	allPlines.append(pline)

	ax = pline.axes
	extraplots.boxoff(ax)
	extraplots.set_ticks_fontsize(ax, fontsize)

	#plt.title(subject+' - '+sessions[0]+'-'+sessions[-1], fontsize=fontsize)
	plt.xlabel('Frequency (kHz)',fontsize=fontsize)
	plt.ylabel('Rightward trials (%)',fontsize=fontsize)
	extraplots.set_ticks_fontsize(plt.gca(),fontsize)
	plt.setp(pline, color='k')
	plt.setp(pcaps, color='k')
	plt.setp(pbars, color='k')
	plt.setp(pdots, markerfacecolor='k')
	legend = plt.legend(allPlines, ['No Laser', 'Laser'])

	plt.hold(True)
	
	laserTrials = valid&(bdata['trialType']==1)
                             color=colours[indCell][laser])
            lines.append(line)
        #plt.legend([lines[-1],lines[0]],['{}, SI = {:.2f}'.format(figLegends[indCell], SIs[1]),'Control, SI = {:.2f}'.format(SIs[0])], loc='best', frameon=False, fontsize=fontSizeLabels)
        plt.legend([lines[-1], lines[0]], [figLegends[indCell], 'Control'],
                   loc='best',
                   frameon=False,
                   fontsize=fontSizeLabels)
        axCurve.annotate(panelLabels[indCell],
                         xy=(labelPosX[0], labelPosY[indCell]),
                         xycoords='figure fraction',
                         fontsize=fontSizePanel,
                         fontweight='bold')
        axCurve.set_ylim(bottom=0)
        axCurve.set_xticks(bands[1:])
        axCurve.tick_params(top=False, right=False, which='both')
        extraplots.boxoff(axCurve)
        extraplots.set_ticks_fontsize(plt.gca(), fontSizeTicks)
        if not indCell:
            axCurve.set_xticklabels('')
        if indCell:
            axCurve.set_xticks(bands)
            bands = bands.tolist()
            bands[-1] = 'WN'
            bands[1::2] = [''] * len(
                bands[1::2])  #remove every other label so x axis less crowded
            axCurve.set_xticklabels(bands)
            plt.xlabel('Bandwidth (oct)', fontsize=fontSizeLabels)
        plt.ylabel('Firing rate (spk/s)', fontsize=fontSizeLabels)
        plt.xlim(-0.1, 7)  #expand x axis so you don't have dots on y axis

if PANELS[1]:
Ejemplo n.º 19
0
def plot_example_with_rate(axRaster, axFR, exampleName, color='k'):

    spikeTimes = exampleSpikeTimes[exampleName]
    indexLimitsEachTrial = exampleIndexLimitsEachTrial[exampleName]
    timeRange = [-0.2, 0.7]
    freqEachTrial = exampleFreqEachTrial[exampleName]
    possibleFreq = np.unique(freqEachTrial)
    freqLabels = ['{0:.0f}'.format(freq) for freq in possibleFreq]
    trialsEachCondition = behavioranalysis.find_trials_each_type(
        freqEachTrial, possibleFreq)
    plt.sca(axRaster)
    pRaster, hCond, zline = extraplots.raster_plot(spikeTimes,
                                                   indexLimitsEachTrial,
                                                   timeRange,
                                                   trialsEachCondition,
                                                   labels=freqLabels)
    plt.setp(pRaster, ms=figparams.rasterMS)

    blankLabels = [''] * 11
    for labelPos in [0, 5, 10]:
        blankLabels[labelPos] = freqLabels[labelPos]

    axRaster.set_yticklabels(blankLabels)

    # ax = plt.gca()
    axRaster.set_xticks([0, 0.5])
    axRaster.set_xlabel('Time from\nsound onset (s)',
                        fontsize=fontSizeLabels,
                        labelpad=-1)
    axRaster.set_ylabel('AM rate (Hz)', fontsize=fontSizeLabels, labelpad=-5)

    # ax.annotate('A', xy=(labelPosX[0],labelPosY[0]), xycoords='figure fraction',
    #             fontsize=fontSizePanel, fontweight='bold')

    countRange = [0.1, 0.5]
    # spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(spikeTimes, indexLimitsEachTrial, countRange)
    # numSpikesInTimeRangeEachTrial = np.squeeze(spikeCountMat)
    numSpikesInTimeRangeEachTrial = np.squeeze(
        np.diff(indexLimitsEachTrial, axis=0))

    if len(numSpikesInTimeRangeEachTrial) == len(freqEachTrial) + 1:
        numSpikesInTimeRangeEachTrial = numSpikesInTimeRangeEachTrial[:-1]
    conditionMatShape = np.shape(trialsEachCondition)
    numRepeats = np.product(conditionMatShape[1:])
    nSpikesMat = np.reshape(numSpikesInTimeRangeEachTrial.repeat(numRepeats),
                            conditionMatShape)
    spikesFilteredByTrialType = nSpikesMat * trialsEachCondition
    avgSpikesArray = np.sum(spikesFilteredByTrialType, 0) / np.sum(
        trialsEachCondition, 0).astype('float') / np.diff(np.array(countRange))
    stdSpikesArray = np.std(spikesFilteredByTrialType, 0) / np.diff(
        np.array(countRange))

    axRate = plt.subplot(axFR)
    plt.sca(axRate)
    nRates = len(possibleFreq)
    plt.hold(True)
    plt.plot(avgSpikesArray,
             range(nRates),
             'ro-',
             mec='none',
             ms=6,
             lw=3,
             color=color)
    plt.plot(avgSpikesArray - stdSpikesArray, range(len(possibleFreq)), 'k:')
    plt.plot(avgSpikesArray + stdSpikesArray, range(len(possibleFreq)), 'k:')
    axRate.set_ylim([-0.5, nRates - 0.5])
    axRate.set_yticks(range(nRates))
    axRate.set_yticklabels([])

    # ax = plt.gca()
    axRate.set_xlabel('Firing rate\n(spk/s)',
                      fontsize=fontSizeLabels,
                      labelpad=-1)
    extraplots.boxoff(axRate)
Ejemplo n.º 20
0
    plt.setp(markers, ms=dataMS)

    plt.hold(1)
    medline(np.median(acPopStat), 1, 0.5)
    plt.hold(1)

    axSummary.set_yticks(yticks)
    axSummary.set_yticklabels(ytickLabels)

    # tickLabels = ['ATh:Str\nn={}'.format(len(thalPopStat)), 'AC:Str\nn={}'.format(len(acPopStat))]
    tickLabels = ['ATh:Str', 'AC:Str']
    axSummary.set_xticks(range(2))
    axSummary.set_xticklabels(tickLabels, rotation=45)
    axSummary.set_xlim([-0.5, 1.5])
    extraplots.set_ticks_fontsize(axSummary, fontSizeLabels)
    extraplots.boxoff(axSummary)
    # axSummary.set_yticks(np.unique(thalPopStat))
    # axSummary.set_yticklabels(possibleFreqLabels)
    # axSummary.set_ylim([-0.001, 0.161])

    yDataMax = max([max(acPopStat), max(thalPopStat)])
    yStars = yDataMax + yDataMax * starYfactor
    yStarHeight = (yDataMax * starYfactor) * starHeightFactor

    zVal, pVal = stats.mannwhitneyu(thalPopStat, acPopStat)
    messages.append("{} p={}".format(popStatCol, pVal))
    # if pVal < 0.05:
    #     extraplots.new_significance_stars([0, 1], np.log(170), np.log(1.1), starMarker='*',
    #                                         fontSize=fontSizeStars, gapFactor=starGapFactor)
    # else:
    #     extraplots.new_significance_stars([0, 1], np.log(170), np.log(1.1), starMarker='n.s.',
                             capthick=1)
            patches.append(
                mpatches.Patch(color=bandColours[band], label=numBands[band]))
        plt.legend(handles=patches,
                   borderaxespad=0.3,
                   prop={'size': 12},
                   loc='best')

        axPsyCurve.set_xticks(range(len(numSNRs)))
        axPsyCurve.set_xticklabels(numSNRs)
        axPsyCurve.set_xlabel('SNR (dB)')

        axPsyCurve.set_ylim(0, 100)
        axPsyCurve.set_ylabel('% trials tone reported')

        extraplots.boxoff(axPsyCurve)

        # -- plot accuracies for each bandwidth and laser presentation --
        axAccuracy = plt.subplot(gs[0, 1])

        barLoc = np.array([-0.24, 0.24])
        xLocs = np.arange(len(numBands))
        xTickLabels = numBands

        for band in range(len(numBands)):
            accuracy = np.zeros(len(numLasers))
            for laser in range(len(numLasers)):
                accuracy[laser] = 100.0 * np.sum(
                    correct[trialsEachCond[:, laser, band]]) / np.sum(
                        valid[trialsEachCond[:, laser, band]])
    plt.axvline(x=0, linewidth=1, color='darkgrey')
    plt.xlim(timeRange)
    yLims = [0, 50]
    soundBarHeight = 0.1 * yLims[-1]
    plt.fill([0, 0.1, 0.1, 0],
             yLims[-1] + np.array([0, 0, soundBarHeight, soundBarHeight]),
             ec='none',
             fc=soundColor,
             clip_on=False)
    plt.ylim(yLims)
    plt.yticks(yLims)
    plt.xticks(np.arange(-0.2, 0.6, 0.2))
    plt.xlabel('Time from sound onset (s)', fontsize=fontSizeLabels)
    plt.ylabel('Firing rate\n(spk/s)',
               fontsize=fontSizeLabels)  #, labelpad=labelDis)
    extraplots.boxoff(plt.gca())

# -- Panel C: representative sound-evoked raster from psychometric task, modulated -- #
#ax4 = plt.subplot(gs[2, 0:2])
ax4 = plt.subplot(gs01[0:2, 0:])
ax4.annotate('C',
             xy=(labelPosX[1], labelPosY[1]),
             xycoords='figure fraction',
             fontsize=fontSizePanel,
             fontweight='bold')

if PANELS[1]:
    rasterFilename = 'example_psychometric_midfreq_soundaligned_raster_test089_20160124a_T4_c6.npz'
    rasterFullPath = os.path.join(dataDir, rasterFilename)
    rasterExample = np.load(rasterFullPath)
Ejemplo n.º 23
0
amplitudeColor = cp.TangoPalette['ScarletRed1']
distanceColor = cp.TangoPalette['SkyBlue2']
velocityColor = cp.TangoPalette['Chameleon3']
markerSize = 8

fig = plt.gcf()
fig.clf()
fig.set_facecolor('w')

gs = gridspec.GridSpec(2, 3)
gs.update(left=0.15, right=0.85, wspace=1, hspace=0.5)

ax1 = plt.subplot(gs[0, :])
plt.plot(np.random.randn(20),np.random.randn(20),'o-',ms=markerSize, color='0.75',mfc=amplitudeColor,mec='w')
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])
Ejemplo n.º 24
0
rects1 = ax3.bar(ind, 1000*subjectMeans[:,0], width, bottom=0.5, edgecolor='k', facecolor='w', lw=2, label='Saline', align='edge')
rects2 = ax3.bar(ind+width+0.015, 1000*subjectMeans[:,1], width, bottom=0.5, edgecolor=muscimolColor, lw=2, facecolor='w', label='Muscimol', align='edge')

# plt.ylim([250,730])
ymax = 730
ymin = 250
plt.ylim([ymin,ymax])
xticks = range(5)
xticklabels = range(1,6)
plt.ylabel('Time from center port exit\nto reward port entry (ms)')
plt.xlabel('Mouse')
ax3.set_xlim([ind[0]-0.5*width, ind[-1]+2.5*width ])
ax3.set_xticks(ind + width)
ax3.set_xticklabels(np.arange(6)+1, fontsize=fontSizeTicks)
extraplots.boxoff(ax3)
for sigSubjectInd in [4]:
    extraplots.significance_stars([sigSubjectInd+0.5*width,sigSubjectInd+1.5*width], ymax, (ymax-ymin)*starLineHeightFactor, starSize=6, gapFactor=0.4, color='0.5')
    # extraplots.significance_stars(sigSubjectInd+np.array([-0.25,0.25]), 710, 25, starSize=6, gapFactor=0.4, color='0.5')

# -- Stats -- #
for inds, subject in enumerate(subjects):
    zScore, pVal = stats.ranksums(centerToSideFile['{}validmeansaline'.format(subject)], centerToSideFile['{}validmeanmuscimol'.format(subject)])
    print 'For mouse {}, using only mean of valid trials in saline condition and in muscimol condition in a ranksums test, p value for the difference in time from centerOut to sideIn is {}.'.format(inds+1, pVal)

# -- Panel C: response times -- #
ax4 = plt.subplot(gs[1, 0])
soundToCoutFilename = 'muscimol_response_time_summary.npz'
soundToCoutFullPath = os.path.join(dataDir,soundToCoutFilename)
soundToCoutFile = np.load(soundToCoutFullPath)
        colorEachCond=colorEachCond,
        fillWidth=None,
        labels=None)

    plt.setp(pRaster, ms=msRaster)

    soundTimesFromEventOnset = intData['soundTimesFromEventOnset']
    trialsToUse = np.sum(trialsEachCond, axis=1).astype('bool')
    yLims = plt.gca().get_ylim()
    plt.hold('on')
    bplot = plt.boxplot(soundTimesFromEventOnset[trialsToUse],
                        sym='',
                        vert=False,
                        positions=[yLims[-1] * 1.05],
                        widths=[yLims[-1] * 0.04])
    extraplots.boxoff(plt.gca())
    plt.autoscale(enable=True, axis='y', tight=True)
    #plt.axis('off')
    for element in ['boxes', 'whiskers', 'fliers', 'caps']:
        plt.setp(bplot[element], color='grey', linewidth=1)
    plt.setp(bplot['whiskers'], linestyle='-')
    plt.setp(bplot['medians'], color='orange')

    sideInTimesFromEventOnset = intData['sideInTimesFromEventOnset']
    plt.hold('on')
    bplot = plt.boxplot(sideInTimesFromEventOnset[trialsToUse],
                        sym='',
                        vert=False,
                        positions=[yLims[-1] * 1.05],
                        widths=[yLims[-1] * 0.04])
    extraplots.boxoff(plt.gca())
        pdots = ax1.plot(logPossibleValues, 100*fractionHitsEachValue, 'o', ms=6, mec='None', mfc=color,
                         clip_on=False)

        #ax1.set_xticks(logPossibleValues)
        #freqLabels = ['{:.03}'.format(x) for x in possibleValues/1000.0]
        #ax1.set_xticklabels(freqLabels)
        #ax1.set_xlabel('Frequency (kHz)', fontsize=fontSizeLabels)

        pfit, = ax1.plot(fitxvals, 100*fityvals, color=color, lw=2, clip_on=False)
        plotHandles.append(pfit)

    ax1.annotate('B', xy=(labelPosX[0],labelPosY[0]), xycoords='axes fraction',
                 fontsize=fontSizePanel, fontweight='bold')

    extraplots.boxoff(ax1)

    #xticks = ax1.get_xticks()
    #newXtickLabels = np.logspace(xticks[0], xticks[-1], 3, base=2)
    #ax1.set_xticks(np.log2(np.array(newXtickLabels)))
    #ax1.set_xticklabels(['{:.3}'.format(x/1000.0) for x in newXtickLabels])

    xTicks = np.array([6,11,19])
    ax1.set_xticks(np.log2(xTicks*1000))
    freqLabels = ['{:d}'.format(x) for x in xTicks]
    ax1.set_xticklabels(freqLabels)
    ax1.set_xlabel('Frequency (kHz)', fontsize=fontSizeLabels)
    ax1.set_xlim([fitxvals[0],fitxvals[-1]])

    ax1.set_ylim([0, 100])
    ax1.set_ylabel('Rightward trials (%)', fontsize=fontSizeLabels)
Ejemplo n.º 27
0
            lines.append(line)
        #plt.legend([lines[-1],lines[0]],['{}, SI = {:.2f}'.format(figLegends[indCell], SIs[1]),'Control, SI = {:.2f}'.format(SIs[0])], loc='best', frameon=False, fontsize=fontSizeLabels)
        plt.legend([lines[-1], lines[0]], [figLegends[indCell], 'control'],
                   loc=legendLocs[indCell],
                   frameon=False,
                   fontsize=fontSizeLegend,
                   borderpad=2.0)
        axCurve.annotate(panelLabels[indCell],
                         xy=(labelPosX[2], labelPosY[indCell]),
                         xycoords='figure fraction',
                         fontsize=fontSizePanel,
                         fontweight='bold')
        axCurve.set_ylim(bottom=0)
        axCurve.set_xticks(bands[1:])
        axCurve.tick_params(top=False, right=False, which='both')
        extraplots.boxoff(axCurve)
        extraplots.set_ticks_fontsize(plt.gca(), fontSizeTicks)
        #         if not indCell:
        #             axCurve.set_xticklabels('')
        #         if indCell:
        #axCurve.set_xticks(bands)
        bands = bands.tolist()
        bands[-1] = 'WN'
        #bands[1::2] = ['']*len(bands[1::2]) #remove every other label so x axis less crowded
        axCurve.set_xticklabels(bands[1:])
        #plt.xticks(rotation=-45)
        plt.xlabel('Bandwidth (oct)', fontsize=fontSizeLabels)
        plt.ylabel('Firing rate (spk/s)', fontsize=fontSizeLabels)
        plt.xlim(0.2, 7)  #expand x axis so you don't have dots on y axis

# bottom three panels have their own gridspec of sorts
    pRaster, hcond, zline = extraplots.raster_plot(spikeTimesFromEventOnset,
                                                   indexLimitsEachTrial,
                                                   timeRangeSound,
                                                   trialsEachCond=trialsEachCond,
                                                   colorEachCond=colorEachFreq,
                                                   labels=labels)
    plt.setp(pRaster, ms=msRaster)
    plt.setp(hcond,zorder=3)

    movementTimesFromEventOnset = rasterExample['movementTimesFromEventOnset']
    trialsToUse = np.sum(trialsEachCond, axis=1).astype('bool')
    yLims = plt.gca().get_ylim()
    plt.hold('on')
    bplot = plt.boxplot(movementTimesFromEventOnset[trialsToUse], sym='', vert=False, positions=[yLims[-1]+15], widths=[25])
    extraplots.boxoff(plt.gca())
    plt.autoscale(enable=True, axis='y', tight=True)
    plt.axis('off')
    for element in ['boxes', 'whiskers', 'fliers', 'caps']:
        plt.setp(bplot[element], color='grey', linewidth=1)
    plt.setp(bplot['whiskers'], linestyle='-')
    plt.setp(bplot['medians'], color='orange')

    #plt.xlabel('Time from sound onset (s)',fontsize=fontSizeLabels, labelpad=labelDis)
    plt.gca().set_xticklabels('')
    plt.ylabel('Frequency (kHz)',fontsize=fontSizeLabels) #, labelpad=labelDis)
    plt.xlim(timeRangeSound[0],timeRangeSound[1])

    ax6 = plt.subplot(gs00[3,:])

    psthFilename = 'example_freq_tuning_2afc_psth_adap017_20160317a_T5_c3.npz' 
Ejemplo n.º 29
0
    nD1PopStat = nD1[popStatCol][pd.notnull(nD1[popStatCol])]

    pos = jitter(np.ones(len(nD1PopStat))*0, 0.20)
    axBW.plot(pos, nD1PopStat, 'o', mec=colornD1, mfc='None', alpha=markerAlpha)
    medline(axBW, np.median(nD1PopStat), 0, 0.5)
    pos = jitter(np.ones(len(D1PopStat))*1, 0.20)
    axBW.plot(pos, D1PopStat, 'o', mec=colorD1, mfc='None', alpha=markerAlpha)
    medline(axBW, np.median(D1PopStat), 1, 0.5)
    axBW.set_ylabel('BW10', fontsize=fontSizeLabels)

    tickLabels = ['nD1:Str\nn={}'.format(len(nD1PopStat)), 'D1:Str\nn={}'.format(len(D1PopStat))]
    axBW.set_xticks(range(2))
    axBW.set_xlim([-0.5, 1.5])
    ylim = [-0.5, 6]
    axBW.set_ylim(ylim)
    extraplots.boxoff(axBW)
    extraplots.set_ticks_fontsize(axBW, fontSizeTicks)
    axBW.set_xticklabels(tickLabels, fontsize=fontSizeLabels, rotation=45)

    zstat, pVal = stats.mannwhitneyu(nD1PopStat, D1PopStat, alternative='two-sided')  # Nick used stats.ranksum

    messages.append("{} p={}".format(popStatCol, pVal))

    yDataMax = max([max(D1PopStat), max(nD1PopStat)])
    # yStars = yDataMax + yDataMax*starYfactor
    yStars = max(ylim) * 1.05
    yStarHeight = (yDataMax*starYfactor)*starHeightFactor
    plt.sca(axBW)
    starString = None if pVal < 0.05 else 'n.s.'
    extraplots.significance_stars([0, 1], yStars, yStarHeight, starMarker='*',
                                  starSize=fontSizeStars+2, starString=starString,
Ejemplo n.º 30
0
def plot_am_with_rate(subplotSpec,
                      spikeTimes,
                      indexLimitsEachTrial,
                      currentFreq,
                      uniqFreq,
                      color='k'):
    fig = plt.gcf()

    gs = gridspec.GridSpecFromSubplotSpec(4,
                                          4,
                                          subplot_spec=subplotSpec,
                                          wspace=-0.45,
                                          hspace=0.0)

    axRaster = plt.ubplot(fig, specRaster)
    # Possible issue in matplotlib backend preventing subplot from working properly. Based on pylab we use TkAgg
    fig.add_subplot(axRaster)
    timeRange = [-0.2, 0.7]
    freqLabels = ['{0:.0f}'.format(freq) for freq in uniqFreq]
    trialsEachCondition = behavioranalysis.find_trials_each_type(
        currentFreq, uniqFreq)
    pRaster, hCond, zline = extraplots.raster_plot(spikeTimes,
                                                   indexLimitsEachTrial,
                                                   timeRange,
                                                   trialsEachCondition,
                                                   labels=freqLabels)
    plt.setp(pRaster, ms=figparams.rasterMS)

    blankLabels = [''] * 11
    for labelPos in [0, 5, 10]:
        blankLabels[labelPos] = freqLabels[labelPos]

    axRaster.set_yticklabels(blankLabels)

    ax = plt.gca()
    ax.set_xticks([0, 0.5])
    ax.set_xlabel('Time from\nsound onset (s)',
                  fontsize=fontSizeLabels,
                  labelpad=-1)
    ax.set_ylabel('AM rate (Hz)', fontsize=fontSizeLabels, labelpad=-5)

    # ax.annotate('A', xy=(labelPosX[0],labelPosY[0]), xycoords='figure fraction',
    #             fontsize=fontSizePanel, fontweight='bold')

    countRange = [0.1, 0.5]
    spikeCountMat = spikesanalysis.spiketimes_to_spikecounts(
        spikeTimes, indexLimitsEachTrial, countRange)
    # numSpikesInTimeRangeEachTrial = np.squeeze(spikeCountMat)

    numSpikesInTimeRangeEachTrial = np.squeeze(
        np.diff(indexLimitsEachTrial, axis=0))

    if len(numSpikesInTimeRangeEachTrial) == len(currentFreq) + 1:
        numSpikesInTimeRangeEachTrial = numSpikesInTimeRangeEachTrial[:-1]
    conditionMatShape = np.shape(trialsEachCondition)
    numRepeats = np.product(conditionMatShape[1:])
    nSpikesMat = np.reshape(numSpikesInTimeRangeEachTrial.repeat(numRepeats),
                            conditionMatShape)
    spikesFilteredByTrialType = nSpikesMat * trialsEachCondition
    avgSpikesArray = np.sum(spikesFilteredByTrialType, 0) / np.sum(
        trialsEachCondition, 0).astype('float') / np.diff(np.array(countRange))
    stdSpikesArray = np.std(spikesFilteredByTrialType, 0) / np.diff(
        np.array(countRange))

    specRate = gs[0:3, 3]
    axRate = plt.Subplot(fig, specRate)
    fig.add_subplot(axRate)

    nRates = len(uniqFreq)
    plt.hold(True)
    plt.plot(avgSpikesArray,
             range(nRates),
             'ro-',
             mec='none',
             ms=6,
             lw=3,
             color=color)
    plt.plot(avgSpikesArray - stdSpikesArray, range(len(uniqFreq)), 'k:')
    plt.plot(avgSpikesArray + stdSpikesArray, range(len(uniqFreq)), 'k:')
    axRate.set_ylim([-0.5, nRates - 0.5])
    axRate.set_yticks(range(nRates))
    axRate.set_yticklabels([])

    # ax = plt.gca()
    axRate.set_xlabel('Firing rate\n(spk/s)',
                      fontsize=fontSizeLabels,
                      labelpad=-1)
    extraplots.boxoff(axRate)
    # extraplots.boxoff(ax, keep='right')
    return axRaster, axRate
Ejemplo n.º 31
0
    SIs = EXC_CELLS['fitSustainedSuppressionIndexNoZeroHighAmp']

    slope, intercept, rVal, pVal, stdErr = stats.linregress(depths, SIs)

    print "SI vs cortical depth linear regression: \ncorrelation coefficient (r): {}\np Value: {}".format(
        rVal, pVal)

    axScatter = plt.subplot(gs[0, 1])

    plt.hold(True)
    plt.plot(depths, SIs, 'o', color=excColor)
    xvals = np.linspace(-2, 2, 200)
    yvals = slope * xvals + intercept
    plt.plot(xvals, yvals, '--', color=excColor, zorder=-1)
    plt.xlim(-0.1, 1.1)
    plt.ylim(-0.1, 1.1)
    plt.xlabel('Depth from pia \n(fraction cortical width)',
               fontsize=fontSizeLabels)
    plt.ylabel('Suppression Index', fontsize=fontSizeLabels)

    extraplots.boxoff(axScatter)

    axScatter.annotate(panelLabel,
                       xy=(labelPosX[1], labelPosY),
                       xycoords='figure fraction',
                       fontsize=fontSizePanel,
                       fontweight='bold')

if SAVE_FIGURE:
    extraplots.save_figure(figFilename, figFormat, figSize, outputDir)
                         color=thisColor,
                         mec='none',
                         lw=3,
                         ms=10,
                         clip_on=False)
    pHandles.append(thisPlot)
    plt.errorbar(np.arange(len(possibleSNRs)),
                 performance,
                 yerr=[lower, upper],
                 color=thisColor,
                 clip_on=False)

plt.xticks(np.arange(len(possibleSNRs)), possibleSNRs)
plt.xlim([-0.2, len(possibleSNRs) - 1 + 0.2])
plt.ylim((0, 100))
plt.legend(pHandles, ['Control', 'No E cells'],
           loc='upper left',
           numpoints=1,
           markerscale=1,
           handlelength=1.5,
           frameon=False)

extraplots.boxoff(ax1)
#plt.ylabel('Rightward choice (%)', fontsize=fontSizeLabels)
plt.ylabel('Signal detection rate (%)', fontsize=fontSizeLabels)
plt.xlabel('Signal to noise ratio (dB)', fontsize=fontSizeLabels)
plt.show()

if SAVE_FIGURE:
    extraplots.save_figure(figFilename, figFormat, figSize, outputDir)
Ejemplo n.º 33
0
fontSizeTicks = 10

panelsToPlot=[0, 1]

gs = gridspec.GridSpec(5, 1)
# gs.update(left=0.15, right=0.95, bottom=0.15, wspace=0.5, hspace=0.5)

summaryFilename = 'muscimol_reaction_time_summary.npz'
summaryFullPath = os.path.join(dataDir,summaryFilename)
fcFile = np.load(summaryFullPath)

subjects = fcFile['subjects']
conditions = fcFile['conditions']

for indsubject, subject in enumerate(subjects):

    ax = plt.subplot(gs[indsubject, 0])

    #ax.hist(fcFile['{}allsaline'.format(subject)], bins=100, histtype='step', color='k')
    ax.hist(fcFile['{}validsaline'.format(subject)], bins=100, histtype='step', color='k')
    #ax.hist(fcFile['{}allmuscimol'.format(subject)], bins=100, histtype='step', color='r')
    ax.hist(fcFile['{}validmuscimol'.format(subject)], bins=100, histtype='step', color='r')
    ax.set_xlim([0.2, 1.0])
    extraplots.boxoff(ax)
    z, pVal = stats.ranksums(fcFile['{}validsaline'.format(subject)], fcFile['{}validmuscimol'.format(subject)])
    print 'mouse {}'.format(indsubject+1), ' Compare reaction times (side-in minus center-out) between saline and muscimol sessions using ranksum test, p value is {}'.format(pVal)
plt.show()

if SAVE_FIGURE:
    extraplots.save_figure(figFilename, figFormat, figSize, outputDir)
Ejemplo n.º 34
0
ax0.set_xlim([0.8, 2.2])
ax0.set_xticks([1, 2])
ax0.set_xticklabels([])
ax0.set_yticks([0, 0.1, 0.2])
ax0.set_ylim([-0.03, 0.23])
ax0.set_title('Leftward trials', fontsize=fontSizeLabels + 1)
plt.sca(ax0)
extraplots.significance_stars([1, 2],
                              0.2,
                              0.01,
                              starSize=12,
                              starString='n.s.',
                              gapFactor=0.2,
                              color='0.5')
extraplots.set_ticks_fontsize(ax0, fontSizeTicks)
extraplots.boxoff(ax0)
zScore, pVal = stats.wilcoxon(allMiceMeanLeftMore, allMiceMeanRightMore)
print('reaction time leftward p={}'.format(pVal))

ax1.annotate('C',
             xy=(labelPosX[2], labelPosY[0]),
             xycoords='figure fraction',
             fontsize=fontSizePanel,
             fontweight='bold')
allMiceMeanLeftMore = []
allMiceMeanRightMore = []
for (animal, shape) in animalShapes.items():
    reactionTimeRightwardLeftMore = summary[animal +
                                            '_reactionTimeRightChoiceMoreLeft']
    meanReactionTimeRightwardLeftMore = np.mean(reactionTimeRightwardLeftMore)
    reactionTimeRightwardRightMore = summary[
Ejemplo n.º 35
0
                          fontsize=fontSizePanel,
                          fontweight='bold')

        axRaster.annotate(panelTitles[indCell],
                          xy=(cellLabelPosX[indCell], cellLabelPosY[indCell]),
                          xycoords='figure fraction',
                          fontsize=fontSizePanel,
                          fontweight='bold')
        plt.setp(pRaster, ms=3, color='k')

        # is there a better way to remove these things??
        while len(hcond) > 0:
            bar = hcond.pop(0)
            bar.remove()

        extraplots.boxoff(axRaster)
        xticks = np.arange(rasterTimeRange[0], rasterTimeRange[1] + 0.1, 0.1)
        axRaster.set_xticks(xticks)
        if indCell != 2:
            axRaster.set_xticklabels('')
        else:
            plt.xlabel('Time from laser onset (s)', fontsize=fontSizeLabels)
        plt.ylabel('Trial', fontsize=fontSizeLabels)

        yLims = np.array(plt.ylim())
        rect = patches.Rectangle((0, yLims[1] * 1.03),
                                 0.1,
                                 yLims[1] * 0.04,
                                 linewidth=1,
                                 edgecolor=laserColor,
                                 facecolor=laserColor,
Ejemplo n.º 36
0
        labels = ['%.1f' % freq for freq in (2**plt.xticks()[0]) / 1000]
        thisAx.set_xticks(plt.xticks()[0])
        thisAx.set_xticklabels(labels)

        plt.xlim(11.5, 15.5)
        plt.ylim(-0.1, 1.1)
        plt.title("{} cells".format(cellTypeLabels[cellType]),
                  color=cellTypeColours[cellType],
                  fontsize=fontSizeLabels)
        if cellType == 0:
            plt.ylabel('Suppression Index', fontsize=fontSizeLabels)
        else:
            thisAx.set_yticklabels([''])
        if cellType == 1:
            plt.xlabel('Preferred frequency (kHz)', fontsize=fontSizeLabels)
        extraplots.boxoff(thisAx)

    thisAx.annotate(panelLabel,
                    xy=(labelPosX, labelPosY[0]),
                    xycoords='figure fraction',
                    fontsize=fontSizePanel,
                    fontweight='bold')

    # --- plots of suppression index vs AM rate ---
if PANELS[1]:
    dataFullPath = os.path.join(AMDataDir, AMFileName)
    data = np.load(dataFullPath)

    axScatter = plt.subplot(gs[1, 0])

    panelLabel = 'B'