示例#1
0
    def plotContrasts(self,
                      y,
                      colorBy,
                      compareBy,
                      groupBy='Temperature',
                      plot_kwargs=dict()):
        resultsDf = self.resultsDf
        resultsDf[
            'newPlotColumn'] = resultsDf[groupBy] + '  ' + resultsDf[compareBy]
        listIdx = tuple(
            np.unique(resultsDf[groupBy])[0] + '  ' +
            np.unique(resultsDf[compareBy])[::-1])
        for i in range(1, len(np.unique(resultsDf[groupBy]))):
            listIdx = (listIdx,
                       tuple(
                           np.unique(resultsDf[groupBy])[i] + '  ' +
                           np.unique(resultsDf[compareBy])[::-1]))

        print(listIdx)
        customPalette = locoPlotters.espressoCreatePalette(resultsDf[colorBy])
        setFont('Source Sans Bold', 10)
        dabestContrastData = dabest.load(
            resultsDf,
            x='newPlotColumn',  # the default for this test config is to group flies by genotype
            y=y,
            idx=listIdx,
            paired=False)

        fig = dabestContrastData.mean_diff.plot(color_col=colorBy,
                                                custom_palette=customPalette,
                                                **plot_kwargs)
        if len(np.unique(resultsDf[groupBy])) == 1:
            flatListIdxC = [item.split('  ')[1] for item in listIdx]
            flatListIdxG = [item.split('  ')[0] for item in listIdx]
        else:
            flatListIdxC = [item.split('  ')[1] for t in listIdx for item in t]
            flatListIdxG = [item.split('  ')[0] for t in listIdx for item in t]
        fig.axes[0].set_xticklabels(flatListIdxC, rotation=45, ha="right")
        ylim = fig.axes[0].get_ylim()
        for i in range(0, len(np.unique(resultsDf[groupBy]))):
            # fig.axes[0].text(0.5, ylim[1], flatListIdxG[0],  ha="center")
            fig.axes[0].text(0.5 + 2 * i,
                             ylim[1] * 1.1,
                             flatListIdxG[2 * i],
                             ha="center")
        locoUtilities.espressoSaveFig(fig, y + '_contrast',
                                      self.metaDataDf.Date[0],
                                      self.outputFolder)
        return fig
示例#2
0
    def plotBoundedSpeedLines(self,
                              colorBy,
                              row=None,
                              col=None,
                              rp='200s',
                              YLim=None):
        setFont('Source Sans Pro', 14)
        T = self.countLogDf.iloc[:, 0] / 3600
        VV = self.countLogDf.filter(regex='_V')
        self.resultsDf['averageSpeed'] = np.nanmean(VV, axis=0)
        listOfPlots, gp, custom_palette = locoPlotters.subplotRowColColor(
            self.metaDataDf, colorBy, row, col)
        nr, nc = listOfPlots[-1][0][0:2]
        figure, axes = plt.subplots(nrows=nr + 1,
                                    ncols=nc + 1,
                                    squeeze=False,
                                    figsize=(5 * (nc + 1), 5 * (nr + 1)))

        maxYlim = [0] * len(listOfPlots)
        plotNames = []
        for i in range(0, len(listOfPlots)):
            # print(listOfPlots[i])
            ro, co = listOfPlots[i][0][0:2]
            name = listOfPlots[i][1]
            ind = gp[name]
            locoPlotters.plotBoundedLine(T,
                                         VV.iloc[:, ind],
                                         ax=axes[ro, co],
                                         c=custom_palette[name[-1]],
                                         resamplePeriod=rp)
            maxYlim[i] = plt.gca().get_ylim()[1]
            axes[ro, co].set_ylabel('Average Speed (mm/s)')
            axes[ro, co].set_xlabel('Time (hour)')
            axes[ro, co].set_title(name[0] + ' ' + name[1])
            plotNames.append([name[-1]])
        for i in range(0, len(listOfPlots)):
            ro, co = listOfPlots[i][0][0:2]
            if YLim:
                axes[ro, co].set_ylim([0, YLim])
            else:
                axes[ro, co].set_ylim([0, np.max(maxYlim)])
        axes[ro, co].legend(plotNames, loc='upper right')
        plt.show()
        locoUtilities.espressoSaveFig(figure, 'splitTS',
                                      self.metaDataDf.Date[0],
                                      self.outputFolder)

        return figure, axes
示例#3
0
 def plotMeanHeatMaps(self, binSize=0.8, row=None, col=None, verbose=False):
     heatMapOutputDir = self.outputFolder
     if verbose:
         meanHeatmapFig, axes, Hall, resultsDf, smallHeatmapFigs = locoPlotters.espressoPlotMeanHeatmaps(
             self, binSize, verbose)
         locoUtilities.espressoSaveFig(smallHeatmapFigs,
                                       'smallHeatmapFigs',
                                       self.metaDataDf.Date[0],
                                       heatMapOutputDir,
                                       pngDPI=200)
     else:
         meanHeatmapFig, axes, Hall, resultsDf = locoPlotters.espressoPlotMeanHeatmaps(
             self, binSize, row, col, verbose)
     self.resultsDf = resultsDf
     self.heatmapMatrix = Hall
     self.heatmapAxes = axes
     self.meanHeatmapFig = meanHeatmapFig
示例#4
0
 def plotChamberSmallMultiples(self):
     dates = np.unique(self.metaDataDf.Date)
     for i in range(0, len(dates)):
         print(dates[i])
         submeta = self.metaDataDf.loc[self.metaDataDf.Date == dates[i]]
         subcount = self.countLogDf.filter(regex=dates[i])
         chamberSmallsTrack, axarrT = locoPlotters.putThingsInToChamberSubplot(
             subcount, submeta)
         chamberSmallsHeat, axarrH = locoPlotters.putThingsInToChamberSubplot(
             subcount, submeta, locoPlotters.espressoPlotHeatmap)
         OutputDir = self.outputFolder + 'chamberPlots/'
         locoUtilities.espressoSaveFig(chamberSmallsTrack,
                                       'chamberSmallsTrack',
                                       dates[i],
                                       OutputDir,
                                       pngDPI=200)
         locoUtilities.espressoSaveFig(chamberSmallsHeat,
                                       'chamberSmallsHeat',
                                       dates[i],
                                       OutputDir,
                                       pngDPI=200)
示例#5
0
plt.xlabel('Zeitgeber Time (hr)')
plt.fill_between(eightOClocks[2:4],
                 0, [.1, .1],
                 color=wes_colors['midnight'],
                 alpha=0.1)
plt.fill_between(eightOClocks[4:6],
                 0, [.1, .1],
                 color=wes_colors['midnight'],
                 alpha=0.1)

# plt.plot(np.mean(volumePivottedResampled.filter(regex = '_0'), axis = 1), 'r')
# plt.plot(np.mean(volumePivottedResampled.filter(regex = '_1'), axis = 1), 'b')

locoUtilities.espressoSaveFig(f,
                              'FeedV',
                              Long1.metaDataDf.Date[0],
                              Long1.outputFolder,
                              pngDPI=300,
                              tp=False)

#%%
durationPivotted = durationDf.pivot_table(values='Duration-ms',
                                          index=pd.to_datetime(
                                              durationDf.index),
                                          columns='FlyID-Choice',
                                          aggfunc='first')
durationPivotted = durationPivotted.fillna(0)

durationPivottedResampled = durationPivotted.resample('600S').sum()
durationPivottedResampled['Seconds'] = (
    durationPivottedResampled.index -
    durationPivottedResampled.index[0]).total_seconds()
示例#6
0
def espressoPlotMeanHeatmaps(espLocoObj,
                             binSize,
                             row=None,
                             col=None,
                             verbose=False):
    from mpl_toolkits.axes_grid1.inset_locator import inset_axes
    setFont('Source Sans Pro', 12)

    XX = espLocoObj.countLogDf.filter(regex='_X')
    YY = espLocoObj.countLogDf.filter(regex='_Y')
    H = []
    xedges = np.arange(-1, 14, binSize)
    yedges = np.arange(-3, 19, binSize)
    numlist = list(range(0, len(espLocoObj.metaDataDf)))
    smallHeatmapFigs = plt.figure(
        num=1, figsize=[5, np.ceil((len(numlist) + 1) / 5) * 0.8])
    n = 1
    for j in numlist:
        #        plotFunc(X.iloc[:, j-1], Y.iloc[:, j-1], flyGenotype, colorPalette)
        # print(str(j) + ' ' + espLocoObj.metaDataDf.Genotype[j])
        X = XX.iloc[:, j]
        Y = YY.iloc[:, j]
        h, xedges, yedges = np.histogram2d(X[~np.isnan(X)],
                                           Y[~np.isnan(Y)],
                                           bins=[xedges, yedges])
        extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
        if verbose:
            plt.subplot(np.ceil((len(numlist) + 1) / 5), 5, n)
            plt.imshow(h.T, extent=extent, origin='lower', cmap='bone')
        n += 1
        H.append(h)
    Hall = np.dstack(H)
    Hall = Hall / 50 / 60  #originally resampled at 50ms and to convert to minute from second/60
    listOfPlots, gp, custom_palette = subplotRowColColor(
        espLocoObj.metaDataDf, None, row, col)
    nr, nc = listOfPlots[-1][0][0:2]
    meanHeatmapFig, axes = plt.subplots(nrows=nr + 1,
                                        ncols=nc + 1,
                                        figsize=(3 * (nc + 1), 4 * (nr + 1)),
                                        squeeze=False)
    images = []
    for i in range(0, len(listOfPlots)):
        # print(listOfPlots[i])
        ro, co = listOfPlots[i][0][0:2]
        # print(listOfPlots[i][0][0:2])
        name = listOfPlots[i][1]
        # print(name)
        ind = gp[name]
        Hmean = np.mean(Hall[:, :, ind], axis=2)
        setRCParamsAxesTicks(False)
        plt.plot([10, 12], [-1, -1], color='w', linewidth=2)
        plt.text(11, -2, '2 mm', color='w', ha='center')
        images.append(axes[ro, co].imshow(Hmean.T,
                                          extent=extent,
                                          origin='lower',
                                          cmap='bone'))
        axes[ro, co].set_title(name[0] + '\n' + name[1])
        axes[ro, co].label_outer()
    left = np.sum(np.sum(Hall[4:9, 21:25, :], axis=0), axis=0)
    right = np.sum(np.sum(Hall[10:15, 21:25, :], axis=0), axis=0)
    bottom = np.sum(np.sum(Hall[4:15, 4:7, :], axis=0), axis=0)
    resultsDf = espLocoObj.resultsDf

    resultsDf['left'] = left
    resultsDf['right'] = right
    resultsDf['bottom'] = bottom
    resultsDf['LR Preference'] = (resultsDf['left'] - resultsDf['right']) / (
        resultsDf['right'] + resultsDf['left'])
    resultsDf['TB Preference'] = (
        resultsDf['right'] + resultsDf['left'] - resultsDf['bottom']) / (
            resultsDf['bottom'] + resultsDf['right'] + resultsDf['left'])
    vmin = min(image.get_array().min() for image in images)
    vmax = max(image.get_array().max() for image in images)
    norm = colors.Normalize(vmin=vmin, vmax=vmax)
    for im in images:
        im.set_norm(norm)
    axins = inset_axes(
        axes[-1, -1],
        width="5%",  # width = 5% of parent_bbox width
        height="100%",  # height : 50%
        loc='lower left',
        bbox_to_anchor=(1.05, 0., 1, 1),
        bbox_transform=axes[-1, -1].transAxes,
        borderpad=0,
    )
    meanHeatmapFig.colorbar(images[-1], cax=axins, ticks=[0, 5, 10, 15, 20])

    def update(changed_image):
        for im in images:
            if (changed_image.get_cmap() != im.get_cmap()
                    or changed_image.get_clim() != im.get_clim()):
                im.set_cmap(changed_image.get_cmap())
                im.set_clim(changed_image.get_clim())

    for im in images:
        im.callbacksSM.connect('changed', update)
    plt.show()
    meanHeatmapFileName = 'meanHeatmapFig' + '_' + str(col) + '_' + str(
        row) + str(espLocoObj.startMin) + '-' + str(espLocoObj.endMin) + 'min'
    locoUtilities.espressoSaveFig(meanHeatmapFig, meanHeatmapFileName,
                                  espLocoObj.metaDataDf.Date[0],
                                  espLocoObj.outputFolder)
    # locoUtilities.espressoWriteDictToCSV(espLocoObj.outputFolder+meanHeatmapFileName+'_ConditionsTable.csv', gp)
    if verbose:
        return meanHeatmapFig, axes, Hall, resultsDf, smallHeatmapFigs
    else:
        return meanHeatmapFig, axes, Hall, resultsDf