Пример #1
0
    def plot_clustertraces(self, data, classified, filename):

        responsetype_classification = classified[1, :]
        kmeans_classification = classified[2, :]
        pp = PdfPages(
            os.path.join(self.Figure_Directory,
                         filename + '_kmeansbyclassification.pdf'))
        colors = sns.color_palette("Paired", self.numclusters + 1)

        for ii in xrange(0, np.size(self.responsetypeindex) + 1):

            if ii == 0:
                fs = plt.figure()
                count_subplot = 1
            elif ii == np.size(self.responsetypeindex):
                pp.savefig(fs, bbox_inches='tight')
                plt.close()
                pp.close()
                break
            elif count_subplot == 2:
                pp.savefig(fs, bbox_inches='tight')
                plt.close()
                fs = plt.figure()
                count_subplot = 1

            ax1 = fs.add_subplot(2, 1, count_subplot)
            responsetype = np.where(
                responsetype_classification == self.responsetypeindex[ii])[0]
            kmeanstype = np.unique(kmeans_classification[responsetype])
            x = np.linspace(0, np.size(data, 1), np.size(data, 1))
            for jj in iter(kmeanstype):
                y = np.mean(data[kmeans_classification == jj, :], 0)
                error = sem(data[kmeans_classification == jj, :], 0)
                num_such_clusters = np.shape(
                    data[kmeans_classification == jj, :])[0]
                ax1.plot(x,
                         y,
                         label='Cluster %s Cells %s' % (jj, num_such_clusters),
                         color=colors[np.int(jj)],
                         linewidth=3)
                ax1.fill_between(x,
                                 y - error,
                                 y + error,
                                 color=colors[np.int(jj)],
                                 alpha=0.5)

            PlottingTools.format_legend(axis_handle=ax1)
            PlottingTools.format_axis(axis_handle=ax1,
                                      title=self.responsetypelabel[ii],
                                      xlim=[0, np.size(data, 1)],
                                      ylim=[np.min(data),
                                            np.max(data)])

            PlottingTools.plot_vertical_lines_onset(self.stimulus_on_time)
            PlottingTools.plot_vertical_lines_offset(self.stimulus_off_time)
            PlottingTools.plot_stimulus_patch(self.stimulus_on_time,
                                              self.stimulus_off_time,
                                              self.stimulus_types,
                                              axis_handle=ax1)
            count_subplot += 1
    def plot_meankmeanclusters(self, data, idx, numcluster, filename):
        # some plotting using numpy's logical indexing
        pp = PdfPages(os.path.join(self.Figure_Directory, filename + '_Cluster' + str(numcluster) + '.pdf'))
        num_such_clusters = np.zeros((numcluster, 1))
        colors = sns.color_palette("Set1", numcluster)
        count = 0

        if numcluster > 4:
            num_plots_per_subplot = 4
        else:
            num_plots_per_subplot = numcluster

        for jj in xrange(0, numcluster + 1):

            if (np.mod(jj, num_plots_per_subplot) == 0 and jj != 0) or jj == numcluster:
                PlottingTools.format_legend(axis_handle=ax1)

                PlottingTools.plot_vertical_lines_onset(self.stimulus_on_time)
                PlottingTools.plot_vertical_lines_offset(self.stimulus_off_time)
                PlottingTools.plot_stimulus_patch(self.stimulus_on_time, self.stimulus_off_time,
                                                  self.stimulus_types, axis_handle=ax1)

            if jj == 0:
                fs = plt.figure()
                count = 1
            elif jj == numcluster:
                pp.savefig(fs, bbox_inches='tight')
                plt.close()
                pp.close()
                break
            elif np.mod(jj, num_plots_per_subplot) == 0 and count == 1:
                count += 1
            elif np.mod(jj, num_plots_per_subplot) == 0:
                pp.savefig(fs, bbox_inches='tight')
                plt.close()
                fs = plt.figure()
                count = 1

            ax1 = fs.add_subplot(2, 1, count)
            if np.size(data[idx == jj, :]) == 0:
                x = np.linspace(0, np.size(data, 1), np.size(data, 1))
                y = np.zeros(np.size(data, 1))
                ax1.plot(x, y, label='Cluster %s Cells %s' % (jj, 0),
                         color=colors[np.int(jj)], linewidth=3, alpha=0.5)
                continue

            num_such_clusters[jj] = np.shape(data[idx == jj, :])[0]
            x = np.linspace(0, np.size(data, 1), np.size(data, 1))
            y = np.mean(data[idx == jj, :], 0)
            error = sem(data[idx == jj, :], 0)
            ax1.plot(x, y, label='Cluster %s Cells %s' % (jj, num_such_clusters[jj]),
                     color=colors[np.int(jj)], linewidth=3, alpha=0.5)
            ax1.fill_between(x, y - error, y + error, color=colors[np.int(jj)], alpha=0.5)
            PlottingTools.format_axis(axis_handle=ax1, xlim=[0, np.size(data, 1)],
                                      ylim=[np.min(y[:]) - 5, 10])
 def plot_sum_distance(self, sum_distance, filename):
     fs = plt.figure(figsize=(5, 5))
     ax1 = fs.add_subplot(211)
     plt.plot(sum_distance[0, :], sum_distance[1, :], 's-', markersize=10, linewidth=2)
     PlottingTools.format_axis(axis_handle=ax1, xlabel='Clusters', ylabel='Sum Square Distance',
                               xlim=(0, sum_distance[0, -1]))
     ax1 = fs.add_subplot(212)
     plt.plot(sum_distance[0, 1:], sum_distance[1, 1:], 's-', markersize=10, linewidth=2)
     PlottingTools.format_axis(axis_handle=ax1, xlabel='Clusters', ylabel='Sum Square Distance',
                               xlim=(0, sum_distance[0, -1]))
     plt.tight_layout()
     plt.savefig(os.path.join(self.Figure_Directory, filename + '_sumsquaredistance' + '.pdf'), bbox_inches='tight')
Пример #4
0
    def plot_meankmeanclusters(self, data, idx, filename):
        # some plotting using numpy's logical indexing
        pp = PdfPages(
            os.path.join(self.Figure_Directory,
                         filename + '_kmeanclusters.pdf'))
        num_such_clusters = np.zeros((self.numclusters, 1))
        colors = sns.color_palette("Set1", self.numclusters)
        count = 0
        num_plots_per_subplot = 5

        for jj in xrange(0, self.numclusters + 1):

            if np.mod(jj, num_plots_per_subplot) == 0 and (
                    jj != 0 or jj == self.numclusters):
                PlottingTools.format_legend(axis_handle=ax1)
                PlottingTools.format_axis(axis_handle=ax1,
                                          xlim=[0, np.size(data, 1)],
                                          ylim=[np.min(data),
                                                np.max(data)])

                PlottingTools.plot_vertical_lines_onset(self.stimulus_on_time)
                PlottingTools.plot_vertical_lines_offset(
                    self.stimulus_off_time)
                PlottingTools.plot_stimulus_patch(self.stimulus_on_time,
                                                  self.stimulus_off_time,
                                                  self.stimulus_types,
                                                  axis_handle=ax1)

            if jj == 0:
                fs = plt.figure()
                count = 1
            elif jj == self.numclusters:
                pp.savefig(fs, bbox_inches='tight')
                plt.close()
                pp.close()
                break
            elif np.mod(jj, num_plots_per_subplot) == 0 and count == 1:
                count += 1
            elif np.mod(jj, num_plots_per_subplot) == 0:
                pp.savefig(fs, bbox_inches='tight')
                plt.close()
                fs = plt.figure()
                count = 1

            ax1 = fs.add_subplot(2, 1, count)
            num_such_clusters[jj] = np.shape(data[idx == jj, :])[0]
            ax1.plot(np.mean(data[idx == jj, :], 0),
                     label='Cluster %s Cells %s' % (jj, num_such_clusters[jj]),
                     color=colors[jj],
                     linewidth=3,
                     alpha=0.5)
Пример #5
0
    def plot_by_clusters(self, data, idx, savefilename):

        pp = PdfPages(self.FiguresDirectory + filesep + savefilename + '.pdf')

        for ii in self.responsetypeindex:
            cluster_indices = np.where(idx == ii)[0]

            if np.size(cluster_indices):
                with sns.axes_style('darkgrid'):
                    fs = plt.figure(figsize=(5, 3))
                    ax1 = plt.subplot(111)
                    plt.plot(data[:, cluster_indices], alpha=0.5)
                    plt.plot(np.mean(data[:, cluster_indices], 1),
                             'k',
                             linewidth=2)
                    plt.title(self.responsetypelabel[ii])
                    PlottingTools.plot_vertical_lines_onset(
                        self.stimulus_on_time)
                    PlottingTools.plot_vertical_lines_offset(
                        self.stimulus_off_time)
                    PlottingTools.plot_stimulus_patch(self.stimulus_on_time,
                                                      self.stimulus_off_time,
                                                      self.stimulus_types,
                                                      axis_handle=ax1)
                    pp.savefig(fs, bbox_inches='tight')

        pp.close()
        plt.close()
Пример #6
0
    def traces_for_correlation(self, time, filename):
        stim_traces = np.zeros((time, np.size(self.responsetypelabel)))
        stim_time = self.stimulus_off_time[0] - self.stimulus_on_time[0]

        for ii in xrange(0, np.size(self.responsetypelabel)):
            print self.responsetypelabel[ii]
            for jj in xrange(0, np.size(self.stimulus_on_time)):
                if self.responsetypelabel[ii] == 'ON':
                    stim_traces[
                        self.stimulus_on_time[jj]:self.stimulus_off_time[jj] -
                        stim_time / 2, ii] = self.amplitude_trace
                elif self.responsetypelabel[ii] == 'OFF':
                    if jj == np.size(self.stimulus_on_time) - 1:
                        stim_traces[self.stimulus_off_time[jj]:self.
                                    stimulus_off_time[jj] + stim_time,
                                    ii] = self.amplitude_trace
                    else:
                        stim_traces[self.stimulus_off_time[jj]:self.
                                    stimulus_on_time[jj + 1] - stim_time / 2,
                                    ii] = self.amplitude_trace
                elif self.responsetypelabel[ii] == 'Inhibitory':
                    stim_traces[
                        self.stimulus_on_time[jj]:self.stimulus_off_time[jj] -
                        stim_time / 2, ii] = -1.5

        stim_traces_smooth = np.zeros((np.shape(stim_traces)))
        for ii in xrange(0, np.size(self.responsetypelabel)):
            stim_traces_smooth[:, ii] = PlottingTools.smooth_hanning(
                stim_traces[:, ii], window_len=stim_time / 2, window='hanning')
        ax1 = plt.subplot(111)
        plt.plot(stim_traces_smooth, alpha=0.5, linewidth=2)
        PlottingTools.plot_vertical_lines_onset(self.stimulus_on_time)
        PlottingTools.plot_vertical_lines_offset(self.stimulus_off_time)
        PlottingTools.format_legend(legend_string=self.responsetypelabel,
                                    axis_handle=ax1)
        PlottingTools.format_axis(axis_handle=ax1,
                                  ylim=[-4, self.amplitude_trace + 1])
        plt.savefig(os.path.join(self.Figure_Directory,
                                 filename + '_responsetypetraces.png'),
                    bbox_inches='tight')
        plt.close()

        return stim_traces_smooth
    def plot_mean_std_historgram(self, calcium_trace, title_figure, pdf):

        standard_deviation = np.std(calcium_trace, axis=0)
        mean = np.mean(calcium_trace, axis=0)

        fs, axes = plt.subplots(2, 1)
        axes[0].plot(mean,
                     standard_deviation,
                     'o',
                     alpha=0.5,
                     markersize=5,
                     markeredgewidth=1)
        PlottingTools.format_axis(axis_handle=axes[0],
                                  title=title_figure,
                                  xlabel='Mean',
                                  ylabel='Standard Deviation')

        axes[1].hist(standard_deviation)
        PlottingTools.format_axis(axis_handle=axes[1],
                                  xlabel='Distribution of variance')

        pdf.savefig(fs, bbox_inches='tight')
        plt.close()
Пример #8
0
    def plot_by_clusters_byoriginal(self, data, idx, classifiedidx,
                                    savefilename):
        pp = PdfPages(self.FiguresDirectory + filesep + savefilename +
                      '_perclassified.pdf')

        for ii in iter(np.unique(idx)):
            cluster_indices = np.where(idx == ii)[0]
            this_classifiedidx = int(classifiedidx[cluster_indices[0]])
            # print ii, classifiedidx[cluster_indices]

            if np.size(cluster_indices):
                with sns.axes_style('darkgrid'):
                    fs = plt.figure(figsize=(4, 2))
                    ax1 = plt.subplot(111)

                    plt.plot(data[:, cluster_indices], alpha=0.5, linewidth=2)
                    plt.plot(np.mean(data[:, cluster_indices], 1),
                             'k',
                             linewidth=2)

                    plt.title(
                        'This cluster %s was classified as %s with number of cells %s'
                        % (ii, self.responsetypelabel[this_classifiedidx],
                           np.size(cluster_indices)),
                        fontsize=8)
                    PlottingTools.plot_vertical_lines_onset(
                        self.stimulus_on_time)
                    PlottingTools.plot_vertical_lines_offset(
                        self.stimulus_off_time)
                    PlottingTools.plot_stimulus_patch(self.stimulus_on_time,
                                                      self.stimulus_off_time,
                                                      self.stimulus_types,
                                                      axis_handle=ax1)
                    PlottingTools.format_axis(axis_handle=ax1,
                                              xlim=[0, np.size(data, 0)])
                    pp.savefig(fs, bbox_inches='tight')
                    plt.close()

        pp.close()
Пример #9
0
    def get_low_correlation_traces_within_clusters(self, data, centroids, idx,
                                                   filename):

        pp = PdfPages(
            os.path.join(self.Figure_Directory,
                         filename + '_correlationwithcentroids.pdf'))

        for ii in xrange(0, self.numclusters):
            data_thisidx = data[:, idx == ii]
            fs = plt.figure(figsize=(4, 3))
            ax1 = fs.add_subplot(111)
            PlottingTools.plot_vertical_lines_onset(self.stimulus_on_time)
            PlottingTools.plot_vertical_lines_offset(self.stimulus_off_time)
            PlottingTools.format_legend(legend_string=self.responsetypelabel,
                                        axis_handle=ax1)
            plt.plot(centroids[ii, :].T,
                     linewidth=2,
                     color='k',
                     label='Cluster Centroid')
            plt.title('Centroid Number %s' % ii)

            for jj in xrange(0, np.size(data_thisidx, 1)):
                correlation = np.corrcoef(data_thisidx[:, jj],
                                          centroids[ii, :])[0, 1]
                print ii, jj, correlation
                if correlation < 0:
                    plt.plot(data_thisidx[:, jj],
                             linewidth=1,
                             alpha=0.5,
                             label='Cell %s  Correlation %s' %
                             (jj, correlation))

            PlottingTools.format_legend(axis_handle=ax1)
            pp.savefig(bbox_inches='tight')
            plt.close()

        pp.close()
Пример #10
0
    def plot_clustertraces(self, data, idx, classifiedidx, filename):

        responsetype_classification = classifiedidx
        kmeans_classification = idx
        num_cluster_noresponse = np.size(
            np.unique(kmeans_classification[responsetype_classification ==
                                            self.responsetypeindex[-1]]))
        pp = PdfPages(
            os.path.join(self.FiguresDirectory,
                         filename + '_kmeansbyclassification.pdf'))
        colors = sns.color_palette(
            "Paired", self.numclusters - num_cluster_noresponse + 5)

        count = 0
        with sns.axes_style('dark'):
            for ii in xrange(0, np.size(self.responsetypeindex)):

                if ii == 0:
                    fs = plt.figure(figsize=(5, 3))
                    count_subplot = 1
                elif ii == np.size(self.responsetypeindex) - 1:
                    pp.savefig(fs, bbox_inches='tight')
                    plt.close()
                    pp.close()
                    break
                elif count_subplot == 2:
                    pp.savefig(fs, bbox_inches='tight')
                    plt.close()
                    fs = plt.figure(figsize=(5, 3))
                    count_subplot = 1

                ax1 = fs.add_subplot(2, 1, count_subplot)
                responsetype = np.where(responsetype_classification ==
                                        self.responsetypeindex[ii])[0]
                kmeanstype = np.unique(kmeans_classification[responsetype])
                x = np.linspace(0, np.size(data, 1), np.size(data, 1))

                for jj in iter(kmeanstype):
                    y = np.mean(data[kmeans_classification == jj, :], 0)
                    error = sem(data[kmeans_classification == jj, :], 0)
                    num_such_clusters = np.shape(
                        data[kmeans_classification == jj, :])[0]
                    ax1.plot(x,
                             y,
                             label='Cluster %s Cells %s' %
                             (jj, num_such_clusters),
                             color=colors[count],
                             linewidth=0.5)
                    ax1.fill_between(x,
                                     y - error,
                                     y + error,
                                     color=colors[count],
                                     alpha=0.3)
                    count += 1

                PlottingTools.format_axis(axis_handle=ax1,
                                          title=self.responsetypelabel[ii],
                                          xlim=[0, np.size(data, 1)],
                                          ylim=[-2, 4],
                                          zeroline=1)

                PlottingTools.plot_vertical_lines_onset(self.stimulus_on_time)
                PlottingTools.plot_vertical_lines_offset(
                    self.stimulus_off_time)
                PlottingTools.plot_stimulus_patch(self.stimulus_on_time,
                                                  self.stimulus_off_time,
                                                  self.stimulus_types,
                                                  axis_handle=ax1)
                count_subplot += 1
Пример #11
0
    def get_high_correlation_between_on_and_off(self, correlation, data,
                                                classifiedidx, savefilename):
        ON = np.where(classifiedidx == self.responsetypeindex[
            self.responsetypelabel.index('ON')])[0]
        OFF = np.where(classifiedidx == self.responsetypeindex[
            self.responsetypelabel.index('OFF')])[0]
        Inh = np.where(classifiedidx == self.responsetypeindex[
            self.responsetypelabel.index('Inhibitory')])[0]
        print 'Data Size..', np.shape(data)
        print 'NUmber of ON...', np.shape(ON)
        print 'Number of OFF...', np.shape(OFF)
        print 'Number of Inh...', np.shape(Inh)

        stimulus_on_time = self.stimulus_on_time
        stimulus_off_time = self.stimulus_off_time

        pp = PdfPages(
            os.path.join(self.FiguresDirectory,
                         savefilename + '_onoffcorrelation.pdf'))
        count_negative = np.zeros(np.size(classifiedidx))
        threshold = 300

        for jj in ON:
            for kk in OFF:
                # print jj, kk, correlation[jj, kk]
                if correlation[jj, kk] > 0.2:
                    count_negative[jj] += 1

        for kk in OFF:
            for jj in ON:
                # print jj, kk, correlation[jj, kk]
                if correlation[jj, kk] > 0.2:
                    count_negative[kk] += 1

        count = 0
        color = sns.color_palette("Paired", 6)
        fs = plt.figure(figsize=(4, 2))
        ax1 = fs.add_subplot(111)
        print 'Size of positive correlations .. %s \n, Total Number of cells %s \n' % (
            np.shape(np.where(count_negative > threshold)[0]),
            (np.size(ON) + np.size(OFF)))
        for ii in np.where(count_negative > threshold)[0]:
            # print 'Plotting..', ii, count

            plt.plot(data[:, ii],
                     linewidth=2,
                     alpha=0.5,
                     color=color[count],
                     label='Cell %s' % ii)
            count += 1

            if count == 5:
                PlottingTools.format_legend(axis_handle=ax1)
                PlottingTools.plot_vertical_lines_onset(stimulus_on_time)
                PlottingTools.plot_vertical_lines_offset(stimulus_off_time)
                pp.savefig(bbox_inches='tight')
                plt.close()
                count = 0
                fs = plt.figure(figsize=(4, 2))
                ax1 = fs.add_subplot(111)

        data_classified = data[:, np.where(count_negative > threshold)[0]]
        plt.imshow(data_classified.T,
                   vmin=-1,
                   vmax=1,
                   cmap='jet',
                   interpolation='gaussian',
                   aspect='auto')
        PlottingTools.plot_vertical_lines_onset(stimulus_on_time)
        PlottingTools.plot_vertical_lines_offset(stimulus_off_time)
        PlottingTools.format_axis(
            axis_handle=ax1,
            xlim=(0, np.size(data, 0)),
            ylim=(0, np.size(data_classified, 1)),
            xlabel='Time(seconds)',
            ylabel='Cells',
            title='Responses where ON and OFF are correlated')
        plt.grid('off')
        plt.colorbar(ticks=[-1, 0, 1])
        pp.savefig(bbox_inches='tight')
        plt.close()
        classifiedidx[np.where(
            count_negative > threshold)[0]] = self.responsetypeindex[
                self.responsetypelabel.index('NoResponse')]

        plt.close()
        pp.close()

        return classifiedidx
Пример #12
0
    def plot_correlation_coefficient(self, data, fish, classifiedidx,
                                     savefilename):

        # Sort data by reponses - remove those without a response
        without_noresponse = np.where(
            classifiedidx != self.responsetypeindex[-1])[0]
        classifiedidx_noresponse = classifiedidx[without_noresponse]
        data_noresponse = data[
            self.stimulus_on_time[0]:self.stimulus_off_time[-1],
            without_noresponse]
        data_noresponse2 = data[:, without_noresponse]

        sorted_idx = np.argsort(classifiedidx_noresponse)
        print np.shape(sorted_idx), np.shape(without_noresponse)
        sorted_data = data_noresponse[:, sorted_idx]
        correlation = np.corrcoef(sorted_data.T)

        classifiedidx_sorted = classifiedidx_noresponse[sorted_idx]

        boundary_points = np.where(
            (classifiedidx_sorted[1:] - classifiedidx_sorted[:-1]) != 0)[0]
        with sns.axes_style('dark'):
            ax1 = plt.subplot(111)
            plt.imshow(correlation,
                       vmin=-1,
                       vmax=1,
                       cmap='seismic',
                       interpolation='gaussian')
            plt.colorbar(ticks=[-1, 0, 1])
            PlottingTools.format_axis(axis_handle=ax1,
                                      xlabel='Cell Number',
                                      ylabel='Cell Number',
                                      title='Correlation Coefficients')
            for ii in boundary_points:
                plt.axvline(x=ii, linestyle='-', color='k', linewidth=1)
                plt.axhline(y=ii, linestyle='-', color='k', linewidth=1)

            plt.savefig(self.FiguresDirectory + filesep + savefilename +
                        'corrcoef.pdf',
                        bbox_inches='tight')
            plt.close()

            fs = plt.figure(figsize=(5, 3))
            ax1 = fs.add_subplot(111)
            plt.imshow(data_noresponse.T,
                       vmin=-1,
                       vmax=1,
                       cmap='jet',
                       interpolation='gaussian',
                       aspect='auto',
                       origin='lower')
            stimulus_on_time = [
                jj - self.stimulus_on_time[0] for jj in self.stimulus_on_time
            ]
            stimulus_off_time = [
                jj - self.stimulus_on_time[0] for jj in self.stimulus_off_time
            ]
            PlottingTools.plot_vertical_lines_onset(stimulus_on_time)
            PlottingTools.plot_vertical_lines_offset(stimulus_off_time)
            for ii in boundary_points:
                plt.axhline(y=ii, linestyle='-', color='k', linewidth=2)
            PlottingTools.format_axis(axis_handle=ax1,
                                      xlim=(0, np.size(data_noresponse, 0)),
                                      ylim=(0, np.size(data_noresponse, 1)),
                                      xlabel='Time(seconds)',
                                      ylabel='Cells',
                                      title='All Responses')
            plt.colorbar(ticks=[-1, 0, 1])
            plt.savefig(self.FiguresDirectory + filesep + savefilename +
                        'heatmap.pdf',
                        bbox_inches='tight')
            plt.close()

        return correlation, data_noresponse2, classifiedidx_noresponse
    def plot_calcium_signals(self, calcium_trace, pdf):

        # Plot some stuff
        with sns.axes_style('dark'):
            fs = plt.figure()
            gs = plt.GridSpec(2, 1, height_ratios=[2, 1])

            ax1 = fs.add_subplot(gs[0, :])
            plt.imshow(calcium_trace.T,
                       cmap='seismic',
                       aspect='auto',
                       vmin=-2,
                       vmax=2)
            plt.colorbar()
            PlottingTools.plot_vertical_lines_onset(self.stimulus_on_time)
            PlottingTools.plot_vertical_lines_offset(self.stimulus_off_time)
            PlottingTools.format_axis(axis_handle=ax1,
                                      xlabel='Time (seconds)',
                                      ylabel='Cell#',
                                      ylim=[0, np.size(calcium_trace, 1)],
                                      xlim=[0, np.size(calcium_trace, 0)])

            ax2 = fs.add_subplot(gs[1, :])
            plt.plot(np.mean(calcium_trace, 1))
            plt.xlim((0, np.size(calcium_trace, 0)))
            PlottingTools.plot_vertical_lines_onset(self.stimulus_on_time)
            PlottingTools.plot_vertical_lines_offset(self.stimulus_off_time)
            PlottingTools.plot_stimulus_patch(self.stimulus_on_time,
                                              self.stimulus_off_time,
                                              self.stimulus_types,
                                              axis_handle=ax2)
            PlottingTools.format_axis(axis_handle=ax2,
                                      xlabel='Time (seconds)',
                                      ylabel=r'$\delta$' + 'F/F')
            pdf.savefig(fs, bbox_inches='tight')
            plt.close()
 def smooth_calcium_trace(self, calcium_trace, windowlen):
     smoothed_calcium_trace = np.zeros(np.shape(calcium_trace))
     for ss in xrange(0, np.size(calcium_trace, 1)):
         smoothed_calcium_trace[:, ss] = PlottingTools.smooth_hanning(
             calcium_trace[:, ss], windowlen, window='flat')
     return smoothed_calcium_trace
Пример #15
0
    def plot_distance_within_cluster(self, fish_name, distance, rand_distance,
                                     numbercells, numbercells_eachfish):

        pp = PdfPages(
            os.path.join(self.FiguresDirectory, 'Distance_within_Cluster.pdf'))
        for ii in xrange(0, np.size(np.unique(fish_name)) + 2):
            print ii, np.shape(numbercells)

            fs, ((ax1, ax2),
                 (ax3,
                  ax4)) = plt.subplots(2,
                                       2,
                                       figsize=(5, 5),
                                       sharey='row',
                                       sharex='col',
                                       gridspec_kw={'width_ratios': [3, 1]})

            if ii == np.size(np.unique(fish_name)):
                # Stats per response by fish
                this_distance = np.zeros(
                    (np.size(distance, 0) * np.size(distance, 1),
                     np.size(distance, 2)))
                for kk in self.responsetype_index:
                    this_distance[:, kk] = np.ravel(distance[:, :, kk])
                distance_dataframe = pd.DataFrame(
                    this_distance, columns=self.responsetype_label)

                sns.stripplot(data=this_distance,
                              jitter=True,
                              ax=ax3,
                              color=".3")
                sns.boxplot(data=distance_dataframe, ax=ax3, whis=np.inf)

                for nn in xrange(0, np.size(numbercells_eachfish, 0)):
                    ax1.plot(numbercells_eachfish[nn, :],
                             's-',
                             markersize=6,
                             markeredgecolor='black',
                             label='Fish %s' % np.unique(fish_name)[nn])

                PlottingTools.format_legend(axis_handle=ax1)
                PlottingTools.format_axis(axis_handle=ax1, title='All Fish')
                plt.sca(ax1)
                plt.ylim((0, numbercells_eachfish.max()))

            elif ii == np.size(np.unique(fish_name)) + 1:
                # Stats per fish by response
                this_distance = np.zeros(
                    (np.size(distance, 2) * np.size(distance, 1),
                     np.size(distance, 0)))
                for kk in xrange(0, np.size(np.unique(fish_name))):
                    this_distance[:, kk] = np.ravel(distance[kk, :, :])
                distance_dataframe = pd.DataFrame(this_distance,
                                                  columns=np.unique(fish_name))

                sns.stripplot(data=this_distance,
                              jitter=True,
                              ax=ax3,
                              color=".3")
                sns.boxplot(data=distance_dataframe, ax=ax3, whis=np.inf)

                for jj in xrange(0, np.size(numbercells, 2)):
                    print jj
                    y = np.mean(numbercells[:, :, jj], 1)
                    error = sem(numbercells[:, :, jj], 1)
                    sample_95ci = 1.96 * error

                    x = np.linspace(0,
                                    np.size(np.unique(fish_name)),
                                    np.size(np.unique(fish_name)),
                                    endpoint=False)
                    ax1.errorbar(x,
                                 y,
                                 yerr=sample_95ci,
                                 fmt='-s',
                                 markersize=6,
                                 markeredgecolor='black',
                                 label=self.responsetype_label[jj])

                    PlottingTools.format_legend(axis_handle=ax1)
                    plt.sca(ax3)
                    plt.xlabel('Fish Number')

            else:
                this_distance = np.squeeze(distance[ii, :, :])
                this_cells = np.squeeze(numbercells[ii, :, :])
                distance_dataframe = pd.DataFrame(
                    this_distance, columns=self.responsetype_label)

                sns.stripplot(data=this_distance,
                              jitter=True,
                              ax=ax3,
                              color=".3")
                sns.factorplot(data=distance_dataframe,
                               ax=ax3,
                               ci=95,
                               estimator=np.median)

                for jj in xrange(0, np.size(this_cells, 0)):
                    ax1.plot(this_cells[jj, :],
                             's-',
                             markersize=6,
                             markeredgecolor='black',
                             label='Plane ' + str(jj + 1))
                    PlottingTools.format_legend(axis_handle=ax1)
                    PlottingTools.format_axis(axis_handle=ax1,
                                              title='Fish %s' %
                                              np.unique(fish_name)[ii])

            plt.sca(ax4)
            plt.boxplot(rand_distance[:])
            plt.setp(ax4, xticks=[1], xticklabels=['Random Dist'])

            plt.sca(ax3)
            # plt.ylim((0, np.max(this_distance[:]) + 200))
            plt.xticks(rotation=90)

            plt.sca(ax2)
            plt.axis('off')

            PlottingTools.format_axis(axis_handle=ax3,
                                      ylabel='Distance Measure')
            PlottingTools.format_axis(axis_handle=ax1,
                                      ylabel='Percentage Cell')

            plt.tight_layout()
            pp.savefig(fs)
        pp.close()