Example #1
0
    def plot(self, dir_plot):
        """
        Plotting stats about the spikes.
        """
        # pylint: disable=too-many-locals
        data = self.data
        run_param = self.run_param

        # String to put before output to the terminal.
        str_start = self.name
        str_start += " "*(20 - len(self.name)) + ":"

        # Set global matplotlib parameters.
        LFPy_util.plot.set_rc_param()

        # Plot spike amps I {{{1 #
        fname = self.name + '_spike_amps_I'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['r_vec'],
                 data['amps_I_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(data['r_vec'],
                        data['amps_I_mean'] - data['amps_I_std'],
                        data['amps_I_mean'] + data['amps_I_std'],
                        color=lcmaps.get_color(0),
                        alpha=0.2)
        ax.set_ylabel(r"Amplitude \textbf{[\si{\milli\volt}]}")
        ax.set_xlabel(r"Distance from Soma \textbf{[\si{\micro\metre}]}")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} # 
        # {{{ Plot spike amps I log
        fname = self.name + '_spike_amps_I_log'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['r_vec'],
                 data['amps_I_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(data['r_vec'],
                        data['amps_I_mean'] - data['amps_I_std'],
                        data['amps_I_mean'] + data['amps_I_std'],
                        color=lcmaps.get_color(0),
                        alpha=0.2)
        # Ugly way to put in some graphs for power laws.
        # Left side.
        x0 = data['r_vec'][0]
        x1 = data['r_vec'][1]
        y0 = data['amps_I_mean'][0]
        for p in [1.0, 2.0, 3.0]:
            y1 = np.power( 1.0 / data['r_vec'][1], p) * \
                    data['amps_I_mean'][ 0] / \
                    np.power(1.0 / data['r_vec'][0], p)
            ax.plot([x0, x1], [y0, y1], color='black')
            ax.annotate(
                    '-'+str(int(p)), 
                    xy=(x1,y1), 
                    xytext=(x1*1.01, y1*0.95),
                    )
        # Right side.
        x0 = data['r_vec'][-3]
        x1 = data['r_vec'][-1]
        y1 = data['amps_I_mean'][-1]
        for p in [1.0, 2.0, 3.0]:
            y0 = np.power(1.0 / data['r_vec'][-3], p) * \
                    data['amps_I_mean'][-1] / \
                    np.power(1.0 / data['r_vec'][-1], p) 
            ax.plot([x0, x1], [y0, y1], color='black')
            ax.annotate(
                    '-'+str(int(p)), 
                    xy=(x0,y0), 
                    xytext=(x0*0.99, y0*0.95),
                    horizontalalignment='right',
                    )

        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.set_xlim([data['r_vec'].min(), data['r_vec'].max()])
        ticker = mpl.ticker.MaxNLocator(nbins=7)
        ax.xaxis.set_major_locator(ticker)
        ax.xaxis.get_major_formatter().labelOnlyBase = False

        # ticker = mpl.ticker.MaxNLocator(nbins=7)
        # ax.yaxis.set_major_locator(ticker)
        # ax.yaxis.get_major_formatter().labelOnlyBase = False

        # Set a label formatter to use normal numbers.
        ax.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
        ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())

        ax.set_ylabel(r"Amplitude \textbf{[\si{\milli\volt}]}")
        ax.set_xlabel(r"Distance from Soma \textbf{[\si{\micro\metre}]}")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} 
        # Plot spike amps II {{{1 #
        fname = self.name + '_spike_amps_II'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['r_vec'],
                 data['amps_II_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(data['r_vec'],
                        data['amps_II_mean'] - data['amps_II_std'],
                        data['amps_II_mean'] + data['amps_II_std'],
                        color=lcmaps.get_color(0),
                        alpha=0.2)
        ax.set_ylabel("Amplitude")
        ax.set_xlabel("Distance from Soma")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # {{{ Plot spike amps II log
        fname = self.name + '_spike_amps_II_log'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['r_vec'],
                 data['amps_II_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(data['r_vec'],
                        data['amps_II_mean'] - data['amps_II_std'],
                        data['amps_II_mean'] + data['amps_II_std'],
                        color=lcmaps.get_color(0),
                        alpha=0.2)

        # Ugly way to put in some graphs for power laws.
        # Left side.
        x0 = data['r_vec'][0]
        x1 = data['r_vec'][1]
        y0 = data['amps_II_mean'][0]
        for p in [1.0, 2.0, 3.0]:
            y1 = np.power( 1.0 / data['r_vec'][1], p) * \
                    data['amps_II_mean'][ 0] / \
                    np.power(1.0 / data['r_vec'][0], p)
            ax.plot([x0, x1], [y0, y1], color='black')
            ax.annotate(
                    '-'+str(int(p)), 
                    xy=(x1,y1), 
                    xytext=(x1*1.01, y1*0.95),
                    )
        # Right side.
        x0 = data['r_vec'][-3]
        x1 = data['r_vec'][-1]
        y1 = data['amps_II_mean'][-1]
        for p in [1.0, 2.0, 3.0]:
            y0 = np.power(1.0 / data['r_vec'][-3], p) * \
                    data['amps_II_mean'][-1] / \
                    np.power(1.0 / data['r_vec'][-1], p) 
            ax.plot([x0, x1], [y0, y1], color='black')
            ax.annotate(
                    '-'+str(int(p)), 
                    xy=(x0,y0), 
                    xytext=(x0*0.99, y0*0.95),
                    horizontalalignment='right',
                    )

        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.set_xlim([data['r_vec'].min(), data['r_vec'].max()])
        ticker = mpl.ticker.MaxNLocator(nbins=7)
        ax.xaxis.set_major_locator(ticker)
        ax.xaxis.get_major_formatter().labelOnlyBase = False

        # ticker = mpl.ticker.MaxNLocator(nbins=7)
        # ax.yaxis.set_major_locator(ticker)
        # ax.yaxis.get_major_formatter().labelOnlyBase = False

        # Set a label formatter to use normal numbers.
        ax.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
        ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())

        ax.set_ylabel(r"Amplitude \textbf{[\si{\milli\volt}]}")
        ax.set_xlabel(r"Distance from Soma \textbf{[\si{\micro\metre}]}")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} 
        # Plot spike width I {{{1 #
        fname = self.name + '_spike_width_I'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['r_vec'],
                 data['widths_I_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(data['r_vec'],
                        data['widths_I_mean'] - data['widths_I_std'],
                        data['widths_I_mean'] + data['widths_I_std'],
                        color=lcmaps.get_color(0),
                        alpha=0.2)
        ax.set_ylabel("Spike Width")
        ax.set_xlabel("Distance from Soma")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot spike widths II {{{1 #
        fname = self.name + '_spike_width_II'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['r_vec'],
                 data['widths_II_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(
            data['r_vec'],
            data['widths_II_mean'] - data['widths_II_std'],
            data['widths_II_mean'] + data['widths_II_std'],
            color=lcmaps.get_color(0),
            alpha=0.2)
        ax.set_ylabel("Spike Width")
        ax.set_xlabel("Distance from Soma")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot spike widths III {{{1 #
        fname = self.name + '_spike_width_III'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['r_vec'],
                 data['widths_III_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(
            data['r_vec'],
            data['widths_III_mean'] - data['widths_III_std'],
            data['widths_III_mean'] + data['widths_III_std'],
            color=lcmaps.get_color(0),
            alpha=0.2)
        ax.set_ylabel("Spike Width")
        ax.set_xlabel("Distance from Soma")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot morphology xz {{{ #
        LFPy_util.plot.morphology(data['poly_morph_xz'],
                                  data['poly_morph_axon_xz'],
                                  elec_x=data['elec_x'],
                                  elec_y=data['elec_z'],
                                  fig_size=lplot.size_square,
                                  fname=self.name + "_morph_elec_xz",
                                  plot_save_dir=dir_plot,
                                  x_label='x',
                                  y_label='z',
                                  show=False)
        # }}} #
        # Spike to plot.
        elec_index = run_param['n']/2
        # title_str = r"Distance from Soma = \SI{{{}}}{{\micro\metre}}"
        # title_str = title_str.format(round(data['r_vec'][elec_index]),2)
        c = lcmaps.get_short_color_array(2 + 1)
        # Plot middle electrode spike {{{1 #
        fname = self.name + '_middle_elec_spike'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['spikes_t_vec'],
                 data['spikes'][elec_index],
                 color=c[0])
        # Trace I
        plt.plot(data['spikes_t_vec'],
                 data['widths_I_trace'][elec_index],
                 color=c[1],
                 )
        # Trace II
        plt.plot(data['spikes_t_vec'],
                 data['widths_II_trace'][elec_index],
                 color=c[1])
        # plt.title(title_str)
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot middle electrode spike freq {{{1 #
        fname = self.name + '_middle_elec_spike_fourier'
        freq, amp, phase = de.find_freq_and_fft(
            data['dt'],
            data['spikes'][elec_index],
            )
        # Remove the first coefficient as we don't care about the baseline.
        freq = np.delete(freq, 0)
        amp = np.delete(amp, 0)
        # Delete frequencies above the option.
        if self.plot_param['freq_end'] is not None:
            idx = min(
                range(len(freq)), 
                key=lambda i: abs(freq[i] - self.plot_param['freq_end'])
                )
            freq = freq[0:idx]
            amp = amp[0:idx]
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        plt.plot(freq, amp, color=lcmaps.get_color(0))
        # plt.title(title_str)
        ax.set_ylabel(r'Amplitude \textbf[$\mathbf{mV}$\textbf]')
        ax.set_xlabel(r'Frequency \textbf[$\mathbf{kHz}$\textbf]')
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot middle electrode signal {{{1 #
        fname = self.name + '_middle_elec'
        print "plotting            :", fname
        c = lcmaps.get_short_color_array(2 + 1)
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['t_vec'],
                 data['LFP'][elec_index],
                 color=lcmaps.get_color(0))
        # plt.title(title_str)
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot middle electrode signal freq {{{1 #
        fname = self.name + '_middle_elec_fourier'
        freq, amp, phase = de.find_freq_and_fft(
            data['dt'],
            data['LFP'][elec_index],
            )
        # Remove the first coefficient as we don't care about the baseline.
        freq = np.delete(freq, 0)
        amp = np.delete(amp, 0)
        if self.plot_param['freq_end'] is not None:
            idx = min(
                range(len(freq)), 
                key=lambda i: abs(freq[i] - self.plot_param['freq_end'])
                )
            freq = freq[0:idx]
            amp = amp[0:idx]
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        plt.plot(freq, amp, color=lcmaps.get_color(0))
        ax.set_ylabel(r'Amplitude \textbf[$\mathbf{mV}$\textbf]')
        ax.set_xlabel(r'Frequency \textbf[$\mathbf{kHz}$\textbf]')
        # plt.title(title_str)
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #

        if self.plot_param['plot_detailed']:
            # Create the directory if it does not exist.
            sub_dir = os.path.join(dir_plot, self.name + "_detailed")
            if not os.path.exists(sub_dir):
                os.makedirs(sub_dir)
            # t = len(run_param['theta'])
            # p = run_param['n_phi']
            p = 1
            n = run_param['n']
            # This title string should be formatted.
            title_str = r"Distance from Soma = \SI{{{}}}{{\micro\metre}}"

            cnt = 0
            for j in xrange(p):
                for k in xrange(n):
                    title_str_1 = title_str.format(data['r_vec'][k])
                    # Plot all elec spikes {{{1 #
                    fname = self.name + '_elec_p_{}_n_{}'.format(j * 360 / p, k)
                    print "plotting            :", fname
                    c = lcmaps.get_short_color_array(2 + 1)
                    plt.figure(figsize=lplot.size_common)
                    ax = plt.gca()
                    lplot.nice_axes(ax)
                    # Plot
                    plt.plot(data['spikes_t_vec'],
                             data['spikes'][cnt],
                             color=c[0])

                    # Trace I
                    plt.plot(data['spikes_t_vec'],
                             data['widths_I_trace'][cnt],
                             color=c[1],
                             )
                    # Trace II
                    plt.plot(data['spikes_t_vec'],
                             data['widths_II_trace'][cnt],
                             color=c[1])
                    # Trace III
                    plt.plot(data['spikes_t_vec'],
                             data['widths_III_trace'][cnt],
                             color=c[1])
                    # plt.title(title_str_1)
                    # Save plt.
                    lplot.save_plt(plt, fname, sub_dir)
                    plt.close()
                    # 1}}} #
                    # Plot all elec spikes freq {{{1 #
                    # Fourier plot.
                    fname = self.name + '_freq_elec_p_{}_n_{}'.format(j * 360 / p, k)
                    freq, amp, phase = de.find_freq_and_fft(
                        data['dt'],
                        data['spikes'][cnt],
                        )
                    # Remove the first coefficient as we don't care about the baseline.
                    freq = np.delete(freq, 0)
                    amp = np.delete(amp, 0)
                    if self.plot_param['freq_end'] is not None:
                        idx = min(
                            range(len(freq)), 
                            key=lambda i: abs(freq[i] - self.plot_param['freq_end'])
                            )
                        freq = freq[0:idx]
                        amp = amp[0:idx]
                    print "plotting            :", fname
                    plt.figure(figsize=lplot.size_common)
                    ax = plt.gca()
                    lplot.nice_axes(ax)
                    plt.plot(freq, amp, color=c[0])
                    ax.set_ylabel(r'Amplitude \textbf[$\mathbf{mV}$\textbf]')
                    ax.set_xlabel(r'Frequency \textbf[$\mathbf{kHz}$\textbf]')
                    # plt.title(title_str_1)
                    lplot.save_plt(plt, fname, sub_dir)
                    plt.close()
                    # 1}}} #
                    cnt += 1
##############################################################################################

if __name__ == "__main__":
    # Set global matplotlib parameters.
    lplot.set_rc_param()

    ## set parameters
    p = set_parameters()

    ## simulate
    Vm, I = simulate(p)

    print "plotting original signal"
    plt.figure(figsize=lplot.size_common)
    ax = plt.gca()
    lplot.nice_axes(ax)
    ax.set_ylabel(r"Mem. Pot. \textbf{[\si{\milli\volt}]}")
    ax.set_xlabel(r"Time \textbf{[\si{\milli\second}]}")
    plt.plot(p['time'], Vm, color=lcmaps.get_color(0))
    lplot.save_plt(plt, "cs_ap_original_signal", ".")
    plt.close()

    # Remove the preparation part of the signal.
    I = I[int(-p['t_start'] / p['dt']):-1]
    Vm = Vm[int(-p['t_start'] / p['dt']):-1]
    p['time'] = p['time'][int(-p['t_start'] / p['dt']):-1]


    pre_dur = 8.35
    post_dur = 8.35
    spikes, t_vec, _ = LFPy_util.data_extraction.extract_spikes(
Example #3
0
    def plot(self, dir_plot):
        data = self.data
        run_param = self.run_param
        process_param = self.process_param
        # Set global matplotlib parameters.
        LFPy_util.plot.set_rc_param(self.plot_param['use_tex'])

        # Plot Spike Width I hist {{{1 #
        # New plot.
        fname = self.name + '_spike_width_I_hist'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        bins = np.arange(0, 2.5, data['dt'])
        n, _, patches = plt.hist(data['widths_I'], bins)
        ax.set_xlabel("Width Peak-to-peak")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        #  }}} #
        # Plot Spike Width II hist {{{1 #
        # New plot.
        fname = self.name + '_spike_width_II_hist'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        bins = np.arange(0, 2.5, data['dt'])
        n, _, patches = plt.hist(data['widths_II'], bins)
        ax.set_xlabel("Width Peak-to-peak")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        #  }}} #
        # Plot morphology {{{ #
        LFPy_util.plot.morphology(data['poly_morph'],
                                  data['poly_morph_axon'],
                                  elec_x=data['elec_x'],
                                  elec_y=data['elec_y'],
                                  fig_size=lplot.size_square,
                                  fname=self.name + "_morph_elec_xy",
                                  plot_save_dir=dir_plot,
                                  show=False)
        # }}} #
        # Plot 3d points {{{1 #
        # 3D plot.
        fname = self.name + "_elec_pos"
        c = lcmaps.get_short_color_array(5)[2]
        fig = plt.figure(figsize=lplot.size_common)
        ax = fig.add_subplot(111, projection='3d')
        ax.scatter(data['elec_x'], data['elec_y'], data['elec_z'], c=c)
        ax.set_xlim(-run_param['R'], run_param['R'])
        ax.set_ylim(-run_param['R'], run_param['R'])
        ax.set_zlim(-run_param['R'], run_param['R'])
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot spike amps I {{{1 #
        # New plot.
        fname = self.name + '_spike_amps_I'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['bins'],
                 data['amps_I_mean'],
                 color=lplot.color_array_long[0],
                 marker='o',
                 markersize=5)
        ax.fill_between(data['bins'],
                        data['amps_I_mean'] - data['amps_I_std'],
                        data['amps_I_mean'] + data['amps_I_std'],
                        color=lplot.color_array_long[0],
                        alpha=0.2)
        ax.set_ylabel(r"Amplitude \textbf{[\si{\micro\volt}]}")
        ax.set_xlabel(r"Distance from Soma \textbf{[\si{\micro\metre}]}")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot spike amps II {{{1 #
        # New plot.
        fname = self.name + '_spike_amps_II'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['bins'],
                 data['amps_II_mean'],
                 color=lplot.color_array_long[0],
                 marker='o',
                 markersize=5)
        ax.fill_between(data['bins'],
                        data['amps_II_mean'] - data['amps_II_std'],
                        data['amps_II_mean'] + data['amps_II_std'],
                        color=lplot.color_array_long[0],
                        alpha=0.2)
        ax.set_ylabel("Amplitude")
        ax.set_xlabel("Distance from Soma")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot Spike Width I {{{1 #
        # New plot.
        fname = self.name + '_spike_width_I'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['bins'],
                 data['widths_I_mean'],
                 color=lplot.color_array_long[0],
                 marker='o',
                 markersize=5)
        ax.fill_between(data['bins'],
                        data['widths_I_mean'] - data['widths_I_std'],
                        data['widths_I_mean'] + data['widths_I_std'],
                        color=lplot.color_array_long[0],
                        alpha=0.2)
        ax.set_ylabel("Width Type I")
        ax.set_xlabel("Distance from Soma")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        #  }}} #
        # Plot Spike Width II {{{1 #
        # New plot.
        fname = self.name + '_spike_width_II'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['bins'],
                 data['widths_II_mean'],
                 color=lplot.color_array_long[0],
                 marker='o',
                 markersize=5)
        ax.fill_between(data['bins'],
                        data['widths_II_mean'] - data['widths_II_std'],
                        data['widths_II_mean'] + data['widths_II_std'],
                        color=lplot.color_array_long[0],
                        alpha=0.2)
        ax.set_ylabel("Width Type II")
        ax.set_xlabel("Distance from Soma")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        #  }}} #
        # Plot Single Electrodes {{{1 #
        # Title string that can be formatted.
        title_str = r"Distance from Soma = \SI{{{}}}{{\micro\metre}}"
        for i in self.plot_param['elec_to_plot']:
            title_str_1 = title_str.format(round(data['elec_r'][[i]],2))
            fname = self.name + '_elec_{}'.format(i)
            print "plotting            :", fname
            c = lcmaps.get_short_color_array(2 + 1)
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            # Plot
            plt.plot(data['spikes_t_vec'], data['spikes'][i], color=c[0])

            # Trace I
            plt.plot(data['spikes_t_vec'],
                     data['widths_I_trace'][i],
                     color=c[1],
                     )
            # Trace II
            plt.plot(data['spikes_t_vec'],
                     data['widths_II_trace'][i],
                     color=c[1])
            plt.title(title_str_1)
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()
        # }}} #
        # Plot Correlation {{{1 #
        # Correlation scatter plot of spike widths.
        fname = self.name + '_correlation'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.scatter(data['widths_II_original'],
                    data['widths_I_original'],
                    color=lplot.color_array_long[0],
                    marker='x')
        # Add lines to represent the cutoff limits.
        if process_param['assert_width']:
            plt.axhline(
                    process_param['assert_width_I_low'], 
                    color=lcmaps.get_color(0.8),
                    )
            plt.axhline(
                    process_param['assert_width_I_high'], 
                    color=lcmaps.get_color(0.8),
                    )
            plt.axvline(
                    process_param['assert_width_II_low'], 
                    color=lcmaps.get_color(0.8),
                    )
            plt.axvline(
                    process_param['assert_width_II_high'], 
                    color=lcmaps.get_color(0.8),
                    )
        ax.set_xlabel("Spike Width Type II")
        ax.set_ylabel("Spike Width Type I")
        # ax.set_aspect('equal')
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} #
        # Plot Electrode Histo {{{1 #
        fname = self.name + '_r_hist'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.hist(data['elec_r_all'],
                 self.process_param['bins'] - 1,
                 range=(0, data['elec_r_all'].max()),
                 facecolor=lplot.color_array_long[0],
                 alpha=0.5)
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
Example #4
0
    def plot(self, dir_plot):
        """
        Plotting stats about the spikes.
        """
        # pylint: disable=too-many-locals
        data = self.data
        run_param = self.run_param

        # String to put before output to the terminal.
        str_start = self.name
        str_start += " "*(20 - len(self.name)) + ":"

        # Set global matplotlib parameters.
        LFPy_util.plot.set_rc_param()

        # 3D plot {{{1 #
        fname = self.name + "_elec_pos"
        c = lplot.get_short_color_array(5)[2]
        fig = plt.figure(figsize=lplot.size_common)
        ax = fig.add_subplot(111, projection='3d')
        cnt = 0
        for i, theta in enumerate(run_param['theta']):
            for j in xrange(run_param['n_phi']):
                for k in xrange(run_param['n']):
                    ax.scatter(data['elec_x'][cnt],
                               data['elec_y'][cnt],
                               data['elec_z'][cnt],
                               c=c)
                    cnt += 1
        ax.set_xlim(-run_param['R'], run_param['R'])
        ax.set_ylim(-run_param['R'], run_param['R'])
        ax.set_zlim(-run_param['R'], run_param['R'])
        ax.set_xlabel("X axis")
        ax.set_ylabel("Y axis")
        ax.set_zlabel("Z axis")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot spike amps I {{{1 #
        fname = self.name + '_spike_amps_I'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        c = lplot.get_short_color_array(data['amps_I_mean'].shape[0] + 1)
        for t in xrange(data['amps_I_mean'].shape[0]):
            label = r'$\theta = {}\degree$'.format(run_param['theta'][t])
            plt.plot(data['r_vec'],
                     data['amps_I_mean'][t],
                     color=c[t],
                     marker='o',
                     markersize=5,
                     label=label)
            ax.fill_between(data['r_vec'],
                            data['amps_I_mean'][t] - data['amps_I_std'][t],
                            data['amps_I_mean'][t] + data['amps_I_std'][t],
                            color=c[t],
                            alpha=0.2)
        handles, labels = ax.get_legend_handles_labels()
        # Position the legen on the right side of the plot.
        ax.legend(handles,
                  labels,
                  loc='upper left',
                  bbox_to_anchor=(1.0, 1.04), )
        ax.set_ylabel(r"Amplitude \textbf{[\si{\milli\volt}]}")
        ax.set_xlabel(r"Distance from Soma \textbf{[\si{\micro\metre}]}")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} # 
        # {{{ Plot spike amps I log
        fname = self.name + '_spike_amps_I_log'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        c = lplot.get_short_color_array(data['amps_I_mean'].shape[0] + 1)
        for t in xrange(data['amps_I_mean'].shape[0]):
            label = r'$\theta = {}\degree$'.format(run_param['theta'][t])
            plt.plot(data['r_vec'],
                     data['amps_I_mean'][t],
                     color=c[t],
                     marker='o',
                     markersize=5,
                     label=label)
            ax.fill_between(data['r_vec'],
                            data['amps_I_mean'][t] - data['amps_I_std'][t],
                            data['amps_I_mean'][t] + data['amps_I_std'][t],
                            color=c[t],
                            alpha=0.2)
            # # Ugly way to put in some graphs for power laws.
            # # Left side.
            # x0 = data['r_vec'][0]
            # x1 = data['r_vec'][1]
            # y0 = data['amps_I_mean'][t, 0]
            # for p in [1.0, 2.0, 3.0]:
            #     y1 = np.power( 1.0 / data['r_vec'][1], p) * \
            #             data['amps_I_mean'][t, 0] / \
            #             np.power(1.0 / data['r_vec'][0], p)
            #     ax.plot([x0, x1], [y0, y1], color='black')
            # # Right side.
            # x0 = data['r_vec'][-3]
            # x1 = data['r_vec'][-1]
            # y1 = data['amps_I_mean'][t,-1]
            # for p in [1.0, 2.0, 3.0]:
            #     y0 = np.power(1.0 / data['r_vec'][-3], p) * \
            #             data['amps_I_mean'][t, -1] / \
            #             np.power(1.0 / data['r_vec'][-1], p) 
            #     ax.plot([x0, x1], [y0, y1], color='black')
        handles, labels = ax.get_legend_handles_labels()


        # Position the legen on the right side of the plot.
        ax.legend(handles,
                  labels,
                  loc='upper left',
                  bbox_to_anchor=(1.0, 1.04), )
        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.set_xlim([data['r_vec'].min(), data['r_vec'].max()])
        ticker = mpl.ticker.MaxNLocator(nbins=7)
        ax.xaxis.set_major_locator(ticker)
        ax.xaxis.get_major_formatter().labelOnlyBase = False

        # ticker = mpl.ticker.MaxNLocator(nbins=7)
        # ax.yaxis.set_major_locator(ticker)
        # ax.yaxis.get_major_formatter().labelOnlyBase = False

        # Set a label formatter to use normal numbers.
        ax.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
        ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())

        ax.set_ylabel(r"Amplitude \textbf{[\si{\milli\volt}]}")
        ax.set_xlabel(r"Distance from Soma \textbf{[\si{\micro\metre}]}")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} 
        # Plot spike amps II {{{1 #
        fname = self.name + '_spike_amps_II'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        c = lplot.get_short_color_array(data['amps_II_mean'].shape[0] + 1)
        for t in xrange(data['amps_II_mean'].shape[0]):
            label = r'$\theta = {}\degree$'.format(run_param['theta'][t])
            plt.plot(data['r_vec'],
                     data['amps_II_mean'][t],
                     color=c[t],
                     marker='o',
                     markersize=5,
                     label=label)
            ax.fill_between(data['r_vec'],
                            data['amps_II_mean'][t] - data['amps_II_std'][t],
                            data['amps_II_mean'][t] + data['amps_II_std'][t],
                            color=c[t],
                            alpha=0.2)
        handles, labels = ax.get_legend_handles_labels()
        # Position the legen on the right side of the plot.
        ax.legend(handles,
                  labels,
                  loc='upper left',
                  bbox_to_anchor=(1.0, 1.04), )
        ax.set_ylabel("Amplitude")
        ax.set_xlabel("Distance from Soma")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # {{{ Plot spike amps II log
        fname = self.name + '_spike_amps_II_log'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        c = lplot.get_short_color_array(data['amps_II_mean'].shape[0] + 1)
        for t in xrange(data['amps_II_mean'].shape[0]):
            label = r'$\theta = {}\degree$'.format(run_param['theta'][t])
            plt.plot(data['r_vec'],
                     data['amps_II_mean'][t],
                     color=c[t],
                     marker='o',
                     markersize=5,
                     label=label)
            ax.fill_between(data['r_vec'],
                            data['amps_II_mean'][t] - data['amps_II_std'][t],
                            data['amps_II_mean'][t] + data['amps_II_std'][t],
                            color=c[t],
                            alpha=0.2)
        handles, labels = ax.get_legend_handles_labels()


        # Position the legen on the right side of the plot.
        ax.legend(handles,
                  labels,
                  loc='upper left',
                  bbox_to_anchor=(1.0, 1.04), )
        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.set_xlim([data['r_vec'].min(), data['r_vec'].max()])
        ticker = mpl.ticker.MaxNLocator(nbins=7)
        ax.xaxis.set_major_locator(ticker)
        ax.xaxis.get_major_formatter().labelOnlyBase = False

        # ticker = mpl.ticker.MaxNLocator(nbins=7)
        # ax.yaxis.set_major_locator(ticker)
        # ax.yaxis.get_major_formatter().labelOnlyBase = False

        # Set a label formatter to use normal numbers.
        ax.xaxis.set_major_formatter(mpl.ticker.ScalarFormatter())
        ax.yaxis.set_major_formatter(mpl.ticker.ScalarFormatter())

        ax.set_ylabel(r"Amplitude \textbf{[\si{\milli\volt}]}")
        ax.set_xlabel(r"Distance from Soma \textbf{[\si{\micro\metre}]}")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} 
        # Plot spike width I {{{1 #
        fname = self.name + '_spike_width_I'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        c = lplot.get_short_color_array(data['widths_I_mean'].shape[0] + 1)
        for t in xrange(data['widths_I_mean'].shape[0]):
            label = r'$\theta = {}\degree$'.format(run_param['theta'][t])
            plt.plot(data['r_vec'],
                     data['widths_I_mean'][t],
                     color=c[t],
                     marker='o',
                     markersize=5,
                     label=label)
            ax.fill_between(data['r_vec'],
                            data['widths_I_mean'][t] - data['widths_I_std'][t],
                            data['widths_I_mean'][t] + data['widths_I_std'][t],
                            color=c[t],
                            alpha=0.2)
        handles, labels = ax.get_legend_handles_labels()
        # Position the legen on the right side of the plot.
        ax.legend(handles,
                  labels,
                  loc='upper left',
                  bbox_to_anchor=(1.0, 1.04), )
        ax.set_ylabel("Spike Width")
        ax.set_xlabel("Distance from Soma")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot spike widths II {{{1 #
        fname = self.name + '_spike_width_II'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        c = lplot.get_short_color_array(data['widths_II_mean'].shape[0] + 1)
        for t in xrange(data['widths_II_mean'].shape[0]):
            label = r'$\theta = {}\degree$'.format(run_param['theta'][t])
            plt.plot(data['r_vec'],
                     data['widths_II_mean'][t],
                     color=c[t],
                     marker='o',
                     markersize=5,
                     label=label)
            ax.fill_between(
                data['r_vec'],
                data['widths_II_mean'][t] - data['widths_II_std'][t],
                data['widths_II_mean'][t] + data['widths_II_std'][t],
                color=c[t],
                alpha=0.2)
        handles, labels = ax.get_legend_handles_labels()
        # Position the legen on the right side of the plot.
        ax.legend(handles,
                  labels,
                  loc='upper left',
                  bbox_to_anchor=(1.0, 1.04), )
        ax.set_ylabel("Spike Width")
        ax.set_xlabel("Distance from Soma")
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot morphology {{{1 #
        LFPy_util.plot.morphology(data['poly_morph'],
                                  data['poly_morph_axon'],
                                  elec_x=data['elec_x'],
                                  elec_y=data['elec_y'],
                                  fig_size=lplot.size_common,
                                  fname=self.name + "_morph_elec_xy",
                                  plot_save_dir=dir_plot,
                                  show=False)
        # 1}}} #
        # Plot morphology xz {{{ #
        LFPy_util.plot.morphology(data['poly_morph_xz'],
                                  data['poly_morph_axon_xz'],
                                  elec_x=data['elec_x'],
                                  elec_y=data['elec_z'],
                                  fig_size=lplot.size_common,
                                  fname=self.name + "_morph_elec_xz",
                                  plot_save_dir=dir_plot,
                                  show=False)
        # }}} #
        # Spike to plot.
        elec_index = run_param['n']/2
        # title_str = r"Distance from Soma = \SI{{{}}}{{\micro\metre}}"
        # title_str = title_str.format(round(data['r_vec'][elec_index]),2)
        c = lplot.get_short_color_array(2 + 1)
        # Plot middle electrode spike {{{1 #
        fname = self.name + '_middle_elec_spike'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['spikes_t_vec'],
                 data['spikes'][elec_index],
                 color=c[0])
        # Trace I
        plt.plot(data['spikes_t_vec'],
                 data['widths_I_trace'][elec_index],
                 color=c[1],
                 )
        # Trace II
        plt.plot(data['spikes_t_vec'],
                 data['widths_II_trace'][elec_index],
                 color=c[1])
        # plt.title(title_str)
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot middle electrode spike freq {{{1 #
        fname = self.name + '_middle_elec_spike_fourier'
        freq, amp, phase = de.find_freq_and_fft(
            data['dt'],
            data['spikes'][elec_index],
            )
        # Remove the first coefficient as we don't care about the baseline.
        freq = np.delete(freq, 0)
        amp = np.delete(amp, 0)
        # Delete frequencies above the option.
        if self.plot_param['freq_end'] is not None:
            idx = min(
                range(len(freq)), 
                key=lambda i: abs(freq[i] - self.plot_param['freq_end'])
                )
            freq = freq[0:idx]
            amp = amp[0:idx]
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        plt.plot(freq, amp, color=c[0])
        # plt.title(title_str)
        ax.set_ylabel(r'Amplitude \textbf[$\mathbf{mV}$\textbf]')
        ax.set_xlabel(r'Frequency \textbf[$\mathbf{kHz}$\textbf]')
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot middle electrode signal {{{1 #
        fname = self.name + '_middle_elec'
        print "plotting            :", fname
        c = lplot.get_short_color_array(2 + 1)
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['t_vec'],
                 data['LFP'][elec_index],
                 color=c[0])
        # plt.title(title_str)
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #
        # Plot middle electrode signal freq {{{1 #
        fname = self.name + '_middle_elec_fourier'
        freq, amp, phase = de.find_freq_and_fft(
            data['dt'],
            data['LFP'][elec_index],
            )
        # Remove the first coefficient as we don't care about the baseline.
        freq = np.delete(freq, 0)
        amp = np.delete(amp, 0)
        if self.plot_param['freq_end'] is not None:
            idx = min(
                range(len(freq)), 
                key=lambda i: abs(freq[i] - self.plot_param['freq_end'])
                )
            freq = freq[0:idx]
            amp = amp[0:idx]
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        plt.plot(freq, amp, color=c[0])
        ax.set_ylabel(r'Amplitude \textbf[$\mathbf{mV}$\textbf]')
        ax.set_xlabel(r'Frequency \textbf[$\mathbf{kHz}$\textbf]')
        # plt.title(title_str)
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # 1}}} #

        if self.plot_param['plot_detailed']:
            # Create the directory if it does not exist.
            sub_dir = os.path.join(dir_plot, self.name + "_detailed")
            if not os.path.exists(sub_dir):
                os.makedirs(sub_dir)
            t = len(run_param['theta'])
            # p = run_param['n_phi']
            p = 1
            n = run_param['n']
            # This title string should be formatted.
            title_str = r"Distance from Soma = \SI{{{}}}{{\micro\metre}}"

            cnt = 0
            for i in xrange(t):
                for j in xrange(p):
                    for k in xrange(n):
                        title_str_1 = title_str.format(data['r_vec'][k])
                        # Plot all elec spikes {{{1 #
                        fname = self.name + '_elec_t_{}_p_{}_n_{}'.format(
                            run_param['theta'][i], j * 360 / p, k)
                        print "plotting            :", fname
                        c = lplot.get_short_color_array(2 + 1)
                        plt.figure(figsize=lplot.size_common)
                        ax = plt.gca()
                        lplot.nice_axes(ax)
                        # Plot
                        plt.plot(data['spikes_t_vec'],
                                 data['spikes'][cnt],
                                 color=c[0])

                        # Trace I
                        plt.plot(data['spikes_t_vec'],
                                 data['widths_I_trace'][cnt],
                                 color=c[1],
                                 )
                        # Trace II
                        plt.plot(data['spikes_t_vec'],
                                 data['widths_II_trace'][cnt],
                                 color=c[1])
                        # plt.title(title_str_1)
                        # Save plt.
                        lplot.save_plt(plt, fname, sub_dir)
                        plt.close()
                        # 1}}} #
                        # Plot all elec spikes freq {{{1 #
                        # Fourier plot.
                        fname = self.name + '_freq_elec_t_{}_p_{}_n_{}'.format(
                            run_param['theta'][i], j * 360 / p, k)
                        freq, amp, phase = de.find_freq_and_fft(
                            data['dt'],
                            data['spikes'][cnt],
                            )
                        # Remove the first coefficient as we don't care about the baseline.
                        freq = np.delete(freq, 0)
                        amp = np.delete(amp, 0)
                        if self.plot_param['freq_end'] is not None:
                            idx = min(
                                range(len(freq)), 
                                key=lambda i: abs(freq[i] - self.plot_param['freq_end'])
                                )
                            freq = freq[0:idx]
                            amp = amp[0:idx]
                        print "plotting            :", fname
                        plt.figure(figsize=lplot.size_common)
                        ax = plt.gca()
                        lplot.nice_axes(ax)
                        plt.plot(freq, amp, color=c[0])
                        ax.set_ylabel(r'Amplitude \textbf[$\mathbf{mV}$\textbf]')
                        ax.set_xlabel(r'Frequency \textbf[$\mathbf{kHz}$\textbf]')
                        # plt.title(title_str_1)
                        lplot.save_plt(plt, fname, sub_dir)
                        plt.close()
                        # 1}}} #
                        cnt += 1
int_amps_I_std     =  int_amps_I_std[start_cutoff:]
int_amps_II        =  int_amps_II[start_cutoff:]
int_amps_II_mean   =  int_amps_II_mean[start_cutoff:]
int_amps_II_std    =  int_amps_II_std[start_cutoff:]
# }}} 

lplot.set_rc_param(True)
lplot.plot_format = ['pdf', 'png']

# {{{ Plot interneuron and pyramidal amp. coefficient of var.
fig, ax = plt.subplots(1,2, 
        sharex=True,
        sharey=True,
        figsize=lplot.size_common)

lplot.nice_axes(ax[0])
lplot.nice_axes(ax[1])
ax[0].set_title('Base-to-Peak $c_v$')
ax[1].set_title('Peak-to-Peak $c_v$')

colors = lcmaps.get_short_color_array(3)

ax[0].plot(
        r,
        pyr_amps_I_std/pyr_amps_I_mean,
        color=colors[0],
        marker='o',
        markersize=5,
        label=pyram,
        )
ax[0].plot(
Example #6
0
    def plot(self, dir_plot):
        data = self.data
        run_param = self.run_param

        # String to put before output to the terminal.
        str_start = self.name
        str_start += " "*(20 - len(self.name)) + ": "

        if self.only_apply_electrode:
            if self.verbose:
                print str_start + "Only apply electrode, nothing to plot."
            return

        # Set global matplotlib parameters.
        LFPy_util.plot.set_rc_param(self.plot_param['use_tex'])

        # New plot.
        fname = self.name + '_all_spikes'
        if run_param['pre_dur'] != 0 and run_param['post_dur'] != 0:
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            ax.set_ylabel(r'Membrane Potential \textbf[$\mathbf{mV}$\textbf]')
            ax.set_xlabel(r'Time \textbf[$\mathbf{ms}$\textbf]')
            lplot.nice_axes(ax)
            rows = data['spikes'].shape[0]
            colors = cmaps.get_short_color_array(rows)
            for row in xrange(rows):
                plt.plot(
                    data['t_vec_spike'], 
                    data['spikes'][row], 
                    color=colors[row],
                    label="Spike {}".format(row)
                    )
                handles, labels = ax.get_legend_handles_labels()
                ax.legend(handles, labels)
            lplot.save_plt(plt, fname, dir_plot)
        else:
            if self.verbose:
                print str_start + " Missing pre and post dur, not plotting " + fname

        # New plot.
        fname = self.name + '_soma_mem'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        ax.set_ylabel(r'Membrane Potential \textbf[$\mathbf{mV}$\textbf]')
        ax.set_xlabel(r'Time \textbf[$\mathbf{ms}$\textbf]')
        lplot.nice_axes(ax)
        plt.plot(data['soma_t'], data['soma_v'], color=cmaps.get_color(0))
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()

        # New plot.
        fname = self.name + '_soma_v_mem_i_mem'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)

        ax = plt.subplot(2, 1, 1)
        lplot.nice_axes(ax)
        plt.plot(data['soma_t'], data['soma_v'], color=cmaps.get_color(0))
        ax.set_ylabel(r'Membrane Potential \textbf[$\mathbf{mV}$\textbf]')

        ax = plt.subplot(2, 1, 2)
        lplot.nice_axes(ax)
        plt.plot(data['soma_t'], data['stimulus_i'], color=cmaps.get_color(0))

        ax.set_ylabel(r'Stimulus Current \textbf[$\mathbf{nA}$\textbf]')
        ax.set_xlabel(r'Time \textbf[$\mathbf{ms}$\textbf]')
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
Example #7
0
    def plot(self, dir_plot):
        """
        Plotting stats about the spikes.
        """
        # pylint: disable=too-many-locals
        data = self.data
        run_param = self.run_param

        # String to put before output to the terminal.
        str_start = self.name
        str_start += " "*(20 - len(self.name)) + ":"

        # Set global matplotlib parameters.
        LFPy_util.plot.set_rc_param()

        # {{{ Plot Ext. Elec. Overlay
        fname = self.name + '_ext_all'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        for i in xrange(run_param['N']):
            # Plot
            plt.plot(data['spikes_t_vec'],
                     data['spikes'][i]/np.abs(data['spikes'][i].min()),
                     color=lcmaps.get_color(0),
                     alpha=0.3,
                     )
            ax.set_xlabel(r"Time \textbf{[\si{\milli\second}]}")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} 
        # {{{ Plot Ext. Elec. Fourier
        freq = data['freq']
        amps = data['amp']
        if self.plot_param['freq_end'] is not None:
            idx = min(
                range(len(freq)), 
                key=lambda i: abs(freq[i] - self.plot_param['freq_end'])
                )
            freq = freq[0:idx]
            amps = amps[:,:idx]
        for i in xrange(run_param['N']):
            amp = amps[i]
            fname = self.name + '_ext'+str(i+1) + "_fourier"
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            # Plot
            plt.plot(freq, amp, color=lcmaps.get_color(0))
            ax.set_ylabel(r'Amplitude \textbf{[\si{\milli\volt}]}')
            ax.set_xlabel(r'Frequency \textbf{[\si{\kilo\hertz}]}')
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()
        # }}} 
        # {{{ Plot soma voltage.
        fname = self.name + '_soma_mem'
        print "plotting            :", fname
        fig = plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        # Plot
        plt.plot(data['spikes_t_vec'],
                 data['spike_soma'],
                 color=lcmaps.get_color(0),
                 )
        plt.plot(data['spikes_t_vec'],
                 data['width_I_trace_soma'],
                 color=lcmaps.get_color(0.5),
                 )
        plt.plot(data['spikes_t_vec'],
                 data['width_II_trace_soma'],
                 color=lcmaps.get_color(0.5),
                 )

        # Plot annotations type I.
        # Get linesegments from the trace.
        lines_x, lines_y = lplot._get_line_segments(
                data['spikes_t_vec'], 
                data['width_II_trace_soma'],
                )
        width = round(data['width_II_soma'], 3)
        plt.hold('on')
        text = r"\SI{" + str(width) + "}{\milli\second}"
        ax.annotate(text,
                    xy=(lines_x[0, 0] + 0.5*width, lines_y[0, 0]),
                    xycoords='data',
                    xytext=(20, -20),
                    textcoords='offset points',
                    va="center",
                    ha="left",
                    bbox=dict(boxstyle="round4",
                              fc="w"),
                    arrowprops=dict(arrowstyle="-|>",
                                    connectionstyle="arc3,rad=-0.2",
                                    fc="w"), )

        # Plot annotations type II.
        # Get linesegments from the trace.
        lines_x, lines_y = lplot._get_line_segments(
                data['spikes_t_vec'], 
                data['width_I_trace_soma'],
                )
        width = round(data['width_I_soma'], 3)
        plt.hold('on')
        text = r"\SI{" + str(width) + r"}{\milli\second}"
        ax.annotate(text,
                    xy=(lines_x[0, 0] + 0.5*width, lines_y[0, 0]),
                    xycoords='data',
                    xytext=(20, -20),
                    textcoords='offset points',
                    va="center",
                    ha="left",
                    bbox=dict(boxstyle="round4",
                              fc="w"),
                    arrowprops=dict(arrowstyle="-|>",
                                    connectionstyle="arc3,rad=-0.2",
                                    fc="w"), )
        ax.set_ylabel(r"Membrane Potential \textbf{[\si{\milli\volt}]}")
        ax.set_xlabel(r"Time \textbf{[\si{\milli\second}]}")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        # Change size and save again.
        fig.set_size_inches(lplot.size_square)
        lplot.save_plt(plt, fname+'_small', dir_plot)
        plt.close()
        # }}} 
        # {{{ Plot Ext. Elec.
        for i in xrange(run_param['N']):
            fname = self.name + '_ext'+str(i+1)
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            # Plot
            plt.plot(data['spikes_t_vec'],
                     data['spikes'][i],
                     color=lcmaps.get_color(0),
                     )
            plt.plot(data['spikes_t_vec'],
                     data['width_I_trace'][i],
                     color=lcmaps.get_color(0.5),
                     )
            plt.plot(data['spikes_t_vec'],
                     data['width_II_trace'][i],
                     color=lcmaps.get_color(0.5),
                     )
            ax.set_ylabel(r"Potential \textbf{[\si{\micro\volt}]}")
            ax.set_xlabel(r"Time \textbf{[\si{\milli\second}]}")
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()

            fname = self.name + '_ext'+str(i+1)+'_full'
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            # Plot
            plt.plot(data['t_vec'],
                     data['LFP'][i],
                     color=lcmaps.get_color(0),
                     )
            ax.set_ylabel(r"Potential \textbf{[\si{\micro\volt}]}")
            ax.set_xlabel(r"Time \textbf{[\si{\milli\second}]}")
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()
        # }}} 
        # {{{ Morphology
        LFPy_util.plot.morphology(data['poly_morph'],
                                  data['poly_morph_axon'],
                                  elec_x=data['elec_x'],
                                  elec_y=data['elec_y'],
                                  fig_size=lplot.size_square,
                                  fname=self.name + "_morph_elec_xy",
                                  plot_save_dir=dir_plot,
                                  show=False,
                                  numbering=True,
                                  )
        # }}} 
        # {{{ Morphology xz
        LFPy_util.plot.morphology(data['poly_morph_xz'],
                                  data['poly_morph_axon_xz'],
                                  elec_x=data['elec_x'],
                                  elec_y=data['elec_z'],
                                  x_label='x',
                                  y_label='z',
                                  fig_size=lplot.size_square,
                                  fname=self.name + "_morph_elec_xz",
                                  plot_save_dir=dir_plot,
                                  show=False,
                                  numbering=True,
                                  )
Example #8
0
    def plot(self, dir_plot):
        data = self.data
        run_param = self.run_param

        LFPy_util.plot.set_rc_param(self.plot_param['use_tex'])
        LFPy_util.plot.plot_format = self.plot_param['formats']

        # {{{ Plot elec spikes overlay
        # Create the directory if it does not exist.
        for elec in xrange(run_param['n_elec']):
            sub_dir = os.path.join(dir_plot, 'elec_{}_all_spikes'.format(elec))
            if not os.path.exists(sub_dir):
                os.makedirs(sub_dir)
            for i in xrange(run_param['sweeps']):
                fname = self.name + '_elec_all_spikes_sweep_{}'.format(i)
                print "plotting            :", fname
                plt.figure(figsize=lplot.size_common)
                ax = plt.gca()
                lplot.nice_axes(ax)
                for j in xrange(data['spikes_elec'][i][elec].shape[0]):
                    plt.plot(data['spikes_t_vec'],
                             data['spikes_elec'][i][elec][j],
                             color=lcmaps.get_color(0),
                             alpha=0.2,
                             )
                # ax.set_xlabel(r"Stimulus Current \textbf{[\si{\nano\ampere}]}")
                # Save plt.
                lplot.save_plt(plt, fname, sub_dir)
                plt.close()
        # }}} 
        # {{{ Plot soma spikes overlay
        # Create the directory if it does not exist.
        sub_dir = os.path.join(dir_plot, 'soma_all_spikes')
        if not os.path.exists(sub_dir):
            os.makedirs(sub_dir)
        for i in xrange(run_param['sweeps']):
            fname = self.name + '_soma_all_spikes_sweep_{}'.format(i)
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            for j in xrange(data['spikes_soma'][i].shape[0]):
                plt.plot(data['spikes_t_vec'],
                         data['spikes_soma'][i][j],
                         color=lcmaps.get_color(0),
                         alpha=0.2,
                         )
            # ax.set_xlabel(r"Stimulus Current \textbf{[\si{\nano\ampere}]}")
            # Save plt.
            lplot.save_plt(plt, fname, sub_dir)
            plt.close()
        # }}} 
        # Plotting all sweeps {{{ 
        if run_param['sweeps'] <= 10:
            fname = self.name + '_soma_mem'
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            colors = lcmaps.get_short_color_array(run_param['sweeps']+1)
            for i in xrange(run_param['sweeps']):
                plt.plot(data['t_vec'],
                         data['v_vec_soma'][i],
                         color=colors[i],
                         )
            ax.set_xlabel(r"Time \textbf{[\si{\milli\second}]}")
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()
        # }}} 
        # Plotting all sweeps elec {{{ 
        if run_param['sweeps'] <= 10:
            for i in xrange(run_param['n_elec']):
                fname = self.name + '_elec_{}'.format(i)
                print "plotting            :", fname
                plt.figure(figsize=lplot.size_common)
                ax = plt.gca()
                lplot.nice_axes(ax)
                colors = lcmaps.get_short_color_array(run_param['sweeps']+1)
                for j in xrange(run_param['sweeps']):
                    plt.plot(data['t_vec'],
                             data['v_vec_elec'][j, i],
                             color=colors[j],
                             )
                ax.set_xlabel(r"Time \textbf{[\si{\milli\second}]}")
                # Save plt.
                lplot.save_plt(plt, fname, dir_plot)
                plt.close()
        # }}} 
        # {{{ Plot f_i
        fname = self.name + '_f_i'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        plt.plot(data['amps']*1000,
                 data['freqs'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.set_xlabel(r"Stimulus Current \textbf{[\si{\nano\ampere}]}")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} 
        # {{{ Plot spike width over frequency I soma
        fname = self.name + '_soma_width_frequency_I'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        plt.plot(data['freqs'],
                 data['widths_I_soma_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(data['freqs'],
                        data['widths_I_soma_mean'] - data['widths_I_soma_std'],
                        data['widths_I_soma_mean'] + data['widths_I_soma_std'],
                        color=lcmaps.get_color(0),
                        alpha=0.2)
        ax.set_ylabel(r"Peak-to-Peak Width \textbf{[\si{\milli\second}]}")
        ax.set_xlabel(r"Frequency \textbf{[\si{\hertz}]}")
        # ax.set_xlabel(r"Stimulus Current \textbf{[\si{\nano\ampere}]}")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} 
        # {{{ Plot spike width over frequency II soma
        fname = self.name + '_soma_width_frequency_II'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        plt.plot(data['freqs'],
                 data['widths_II_soma_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(data['freqs'],
                        data['widths_II_soma_mean'] - data['widths_II_soma_std'],
                        data['widths_II_soma_mean'] + data['widths_II_soma_std'],
                        color=lcmaps.get_color(0),
                        alpha=0.2)
        ax.set_ylabel(r"Half Max Width \textbf{[\si{\milli\second}]}")
        ax.set_xlabel(r"Frequency \textbf{[\si{\hertz}]}")
        # ax.set_xlabel(r"Stimulus Current \textbf{[\si{\nano\ampere}]}")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} 
        # {{{ Plot spike width over frequency I elec
        for i in xrange(run_param['n_elec']):
            fname = self.name + '_elec_{}_width_frequency_I'.format(i)
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            plt.plot(data['freqs'],
                     data['widths_I_elec_mean'][:, i],
                     color=lcmaps.get_color(0),
                     marker='o',
                     markersize=5,
                     )
            ax.fill_between(
                    data['freqs'],
                    data['widths_I_elec_mean'][:,i] 
                        - data['widths_I_elec_std'][:,i],
                    data['widths_I_elec_mean'][:,i] 
                        + data['widths_I_elec_std'][:,i],
                    color=lcmaps.get_color(0),
                    alpha=0.2)
            ax.set_ylabel(r"Peak-to-Peak Width \textbf{[\si{\milli\second}]}")
            ax.set_xlabel(r"Frequency \textbf{[\si{\hertz}]}")
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()
        # }}} 
        # {{{ Plot spike width over frequency II elec
        for i in xrange(run_param['n_elec']):
            fname = self.name + '_elec_{}_width_frequency_II'.format(i)
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            plt.plot(data['freqs'],
                     data['widths_II_elec_mean'][:,i],
                     color=lcmaps.get_color(0),
                     marker='o',
                     markersize=5,
                     )
            ax.fill_between(
                    data['freqs'],
                    data['widths_II_elec_mean'][:,i] 
                        - data['widths_II_elec_std'][:,i],
                    data['widths_II_elec_mean'][:,i] 
                        + data['widths_II_elec_std'][:,i],
                    color=lcmaps.get_color(0),
                    alpha=0.2)
            ax.set_ylabel(r"Half Max Width \textbf{[\si{\milli\second}]}")
            ax.set_xlabel(r"Frequency \textbf{[\si{\hertz}]}")
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()
        # }}} 
        # {{{ Plot spike width over frequency I elec soma
        for i in xrange(run_param['n_elec']):
            fname = self.name + '_elec_{}_soma_width_frequency_I'.format(i)
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            plt.plot(data['freqs'],
                     data['widths_I_soma_mean'],
                     color=lcmaps.get_color(0),
                     marker='o',
                     markersize=5,
                     label='Soma',
                     )
            ax.fill_between(data['freqs'],
                            data['widths_I_soma_mean'] - data['widths_I_soma_std'],
                            data['widths_I_soma_mean'] + data['widths_I_soma_std'],
                            color=lcmaps.get_color(0),
                            alpha=0.2)
            plt.plot(data['freqs'],
                     data['widths_I_elec_mean'][:, i],
                     color=lcmaps.get_color(0.5),
                     marker='o',
                     markersize=5,
                     label='Elec.'
                     )
            ax.fill_between(
                    data['freqs'],
                    data['widths_I_elec_mean'][:,i] 
                        - data['widths_I_elec_std'][:,i],
                    data['widths_I_elec_mean'][:,i] 
                        + data['widths_I_elec_std'][:,i],
                    color=lcmaps.get_color(0.5),
                    alpha=0.2)
            ax.set_ylabel(r"Peak-to-Peak Width \textbf{[\si{\milli\second}]}")
            ax.set_xlabel(r"Frequency \textbf{[\si{\hertz}]}")
            # handles, labels = ax.get_legend_handles_labels()
            # ax.legend(handles,
            #           labels,
            #           loc='upper right',
            #           # bbox_to_anchor=(1, 0.5), 
            #           )
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()
        # }}} 
        # {{{ Plot spike width over frequency II elec soma
        for i in xrange(run_param['n_elec']):
            fname = self.name + '_elec_{}_soma_width_frequency_II'.format(i)
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            plt.plot(data['freqs'],
                     data['widths_II_soma_mean'],
                     color=lcmaps.get_color(0),
                     marker='o',
                     markersize=5,
                     label='Soma',
                     )
            ax.fill_between(data['freqs'],
                            data['widths_II_soma_mean'] - data['widths_II_soma_std'],
                            data['widths_II_soma_mean'] + data['widths_II_soma_std'],
                            color=lcmaps.get_color(0),
                            alpha=0.2)
            plt.plot(data['freqs'],
                     data['widths_II_elec_mean'][:,i],
                     color=lcmaps.get_color(0.5),
                     marker='o',
                     markersize=5,
                     label='Elec.',
                     )
            ax.fill_between(
                    data['freqs'],
                    data['widths_II_elec_mean'][:,i] 
                        - data['widths_II_elec_std'][:,i],
                    data['widths_II_elec_mean'][:,i] 
                        + data['widths_II_elec_std'][:,i],
                    color=lcmaps.get_color(0.5),
                    alpha=0.2)
            ax.set_ylabel(r"Half Max Width \textbf{[\si{\milli\second}]}")
            ax.set_xlabel(r"Frequency \textbf{[\si{\hertz}]}")
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()
        # }}} 
        # {{{ Plot spike amplitude over frequency I soma
        fname = self.name + '_soma_amp_frequency_I'
        print "plotting            :", fname
        plt.figure(figsize=lplot.size_common)
        ax = plt.gca()
        lplot.nice_axes(ax)
        plt.plot(data['freqs'],
                 data['amps_I_soma_mean'],
                 color=lcmaps.get_color(0),
                 marker='o',
                 markersize=5,
                 )
        ax.fill_between(data['freqs'],
                        data['amps_I_soma_mean'] - data['amps_I_soma_std'],
                        data['amps_I_soma_mean'] + data['amps_I_soma_std'],
                        color=lcmaps.get_color(0),
                        alpha=0.2)
        ax.set_ylabel(r"Base-to-Peak Amp.")
        ax.set_xlabel(r"Frequency \textbf{[\si{\hertz}]}")
        # Save plt.
        lplot.save_plt(plt, fname, dir_plot)
        plt.close()
        # }}} 
        # {{{ Plot spike amplitude over frequency I elec
        for i in xrange(run_param['n_elec']):
            fname = self.name + '_elec_{}_amp_frequency_I'.format(i)
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            plt.plot(data['freqs'],
                     data['amps_I_elec_mean'][:, i],
                     color=lcmaps.get_color(0),
                     marker='o',
                     markersize=5,
                     )
            ax.fill_between(
                    data['freqs'],
                    data['amps_I_elec_mean'][:,i] 
                        - data['amps_I_elec_std'][:,i],
                    data['amps_I_elec_mean'][:,i] 
                        + data['amps_I_elec_std'][:,i],
                    color=lcmaps.get_color(0),
                    alpha=0.2)
            ax.set_ylabel(r"Base-to-Peak Amp.")
            ax.set_xlabel(r"Frequency \textbf{[\si{\hertz}]}")
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()
        # }}} 
        # {{{ Plot spike amplitude over frequency I elec soma
        for i in xrange(run_param['n_elec']):
            fname = self.name + '_elec_{}_soma_amp_frequency_I'.format(i)
            print "plotting            :", fname
            plt.figure(figsize=lplot.size_common)
            ax = plt.gca()
            lplot.nice_axes(ax)
            plt.plot(data['freqs'],
                     data['amps_I_soma_mean'],
                     color=lcmaps.get_color(0),
                     marker='o',
                     markersize=5,
                     label='Soma',
                     )
            ax.fill_between(data['freqs'],
                            data['amps_I_soma_mean'] - data['amps_I_soma_std'],
                            data['amps_I_soma_mean'] + data['amps_I_soma_std'],
                            color=lcmaps.get_color(0),
                            alpha=0.2)
            plt.plot(data['freqs'],
                     data['amps_I_elec_mean'][:, i],
                     color=lcmaps.get_color(0.5),
                     marker='o',
                     markersize=5,
                     label='Elec.'
                     )
            ax.fill_between(
                    data['freqs'],
                    data['amps_I_elec_mean'][:,i] 
                        - data['amps_I_elec_std'][:,i],
                    data['amps_I_elec_mean'][:,i] 
                        + data['amps_I_elec_std'][:,i],
                    color=lcmaps.get_color(0.5),
                    alpha=0.2)
            ax.set_ylabel(r"Base-to-Peak Amp.")
            ax.set_xlabel(r"Frequency \textbf{[\si{\hertz}]}")
            # Save plt.
            lplot.save_plt(plt, fname, dir_plot)
            plt.close()