def test_grid():
    V, t, x, y, trigger, neuron = AxonExperiment(FIGURE_CULTURE).traces(
        FIGURE_NEURON)

    hidens = HidensTransformation(x, y)

    i, j = hidens.xy2ij(x, y)
    xb, yb = hidens.ij2xy(i, j)
    x0, y0 = hidens.ij2xy(0, 0)

    ax1 = plt.subplot(121)
    plt.plot(x, y, 'bx', label='original')
    plt.plot(xb, yb, 'k+', label='backtransformed')
    plt.plot(x0, y0, 'go', label='hexagonal origin (backtransformed)')
    plt.title('cartesian coordinates x,y')
    mea_axes(ax1)
    ax1.set_ylim((-500, 2200))
    plt.legend(numpoints=1)

    ax2 = plt.subplot(122)
    plt.plot(i, j, 'ko', label='transformed')
    plt.plot(0, 0, 'go', label='hexagonal origin')
    plt.title('hexagonal grid index i, j')
    ax2.set_xlim((-1, np.amax(i)))
    ax2.set_ylim((-1, np.amax(j)))
    plt.legend(numpoints=1)

    plt.show()
def test(neuron=1536, method=2):

    path = 'data/neuron%d' % neuron

    # Get traces
    V, t, x, y, trigger, neuron = load_traces(path + '.h5')
    if trigger < 0:  # may added to load_traces with trigger>-1 as condition
        trigger = find_AIS(V)
    t *= 1000  # convert to ms

    print('Time %1.2f .. %1.2f ms ' % (min(t), max(t)))

    # AIS coordinates
    index_AIS = find_AIS(V)
    x_AIS = x[index_AIS]
    y_AIS = y[index_AIS]

    # Negative peak
    Vmin = np.min(V, axis=1)

    # Segmentation
    if method == 1:
        delay, _, _, _, axon = segment_axon_Bakkum(V, t, pnr_threshold=5)
    else:
        neighbors = neighbors_from_electrode_positions(x, y)
        delay, _, std_delay, _, thr, _, _, _, axon = segment_axon_verbose(
            t, V, neighbors)

    print('Axonal delay %1.2f .. %1.2f ms ' %
          (min(delay[axon]), max(delay[axon])))

    ax = plt.subplot(111)
    V2size = lambda x: np.abs(x) * 2
    axh = plot_image_axon_delay_voltage(ax,
                                        path + 'axon',
                                        axon,
                                        delay,
                                        Vmin,
                                        x,
                                        y,
                                        transform=V2size,
                                        alpha=0.5)
    cross_hair(ax, x_AIS, y_AIS, color='red')
    mea_axes(ax)

    # Compare with ground truth
    xg, yg = ImageIterator(path + 'axon').truth()
    H = compare_with_groundtruth(x, y, xg, yg)
    plt.title('Neuron %d, Method %d: H=%1.3f um' % (neuron, method, H))

    plt.show()
Exemple #3
0
def plot_pcg_on_network(ax, polychronous_group, delays, pos):
    """
    Plots a polychronous group onto a structural network. Unfortunately, (re)plotting is slow for large groups.
    :param ax: axis handle
    :param polychronous_group: graph containing the events and connections of a polychronous group
    :param delays: delays between neurons (structural network)
    :param pos: positions of the neurons on the multi electrode array
    """
    plot_neuron_points(ax, unique_neurons(delays), pos)
    plot_network(ax, delays, pos, color='gray')
    for i, ((time1, neuron1),
            (time2, neuron2)) in enumerate(polychronous_group.edges(),
                                           start=1):
        if time2 < time1:
            time1, neuron1, time2, neuron2 = time2, neuron2, time1, neuron1
        highlight_connection(ax, (neuron1, neuron2), pos, linewidth=1)
    mea_axes(ax)
def test_subset():
    V, t, x, y, trigger, neuron = AxonExperiment(FIGURE_CULTURE).traces(
        FIGURE_NEURON)

    hidens = HidensTransformation(x, y)
    xs, ys, Vs = hidens.subset(V)

    ax = plt.subplot(111)
    plt.plot(x,
             y,
             'o',
             markerfacecolor='None',
             markeredgecolor='black',
             label='all')
    plt.plot(xs, ys, 'ko', label='subset')
    mea_axes(ax)
    plt.legend(numpoints=1)

    plt.show()
def make_movie(V, t, x, y, culture, neuron):
    """

    :param V: spike triggered averages (traces) for each electrode
    :param t: time for each frame (relative to trigger, in ms)
    :param x, y: coordinates for each electrode
    :param culture, neuron: for title
    :return: ani: animation handle
    """

    t_ms = t * 1000  # ms
    n_frames = len(t)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_aspect('equal')
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    im = ax.imshow(interpolate_frame(V[:, 0], x, y),
                   extent=[min(x), max(x), max(y),
                           min(y)],
                   cmap='seismic',
                   interpolation='nearest')
    ax.set_title('Culture %d, Neuron %d, Time %1.1f' %
                 (culture, neuron, t_ms[0]))
    voltage_color_bar(im, label=r'$V$ [$\mu$V]', shrink=0.5)
    mea_axes(ax)
    fig.set_size_inches([5, 5])
    plt.tight_layout()

    def update_frame(n):
        tmp = interpolate_frame(V[:, n], x, y)
        im.set_data(tmp)
        ax.set_title('Culture %d, Neuron %d, %1.3f ms' %
                     (culture, neuron, t_ms[n]))
        return im

    ani = animation.FuncAnimation(fig, update_frame, n_frames, interval=30)

    return ani
Exemple #6
0
def make_figure(figurename,
                figpath=None,
                Culture=FIGURE_CULTURE,
                with_background_image=True):

    # make directory
    subfolderpath = os.path.join(figpath, 'neurons')
    if not os.path.exists(subfolderpath):
        os.makedirs(subfolderpath)

    # Load electrode coordinates and calculate neighborhood
    pos = load_positions(mea='hidens')
    x = pos.x
    y = pos.y

    all_triggers, all_AIS, all_axonal_delays, all_dendritic_return_currents = Experiment(
        Culture).compartments()

    for neuron in FIGURE_NEURONS:

        # Plot figure
        fig = plt.figure(figurename, figsize=(8, 7))
        # for example neuron5.png use instead:
        # fig = plt.figure(figurename)
        # fig.set_size_inches([5.5, 5])

        ax = plt.subplot(111)

        # Load and plot background images
        if with_background_image:
            fullfilename = os.path.join(
                Experiment(Culture).data_directory, "neuron%d.png" % neuron)
            raw_image = plt.imread(fullfilename)
            plt.imshow(raw_image,
                       cmap='gray',
                       alpha=0.5,
                       extent=[165.5, 1918.9, 2106.123, 88.123001])

        # Map axons for Bullmann's method
        delay = all_axonal_delays[neuron]
        index_AIS = all_AIS[neuron]
        axon = np.isfinite(delay)
        V, _, _, _, _, _ = Experiment(Culture).traces(neuron)
        # max_axon_delay = np.around(np.nanmax(delay), decimals=1)
        max_axon_delay = 2.5  # same scaling for all neurons

        V2size = lambda x: np.sqrt(np.abs(x)) * 5
        radius = V2size(V)
        ax.scatter(x[axon],
                   y[axon],
                   s=radius[axon],
                   c=delay[axon],
                   marker='o',
                   edgecolor='none',
                   cmap=plt.cm.hsv,
                   vmin=0,
                   vmax=max_axon_delay,
                   alpha=1)

        plt.title('Culture %d, Neuron %d, Delay map' % (Culture, neuron))

        if with_background_image:
            # cross_hair(ax, x[index_AIS], y[index_AIS], color='red')
            mea_axes(ax)
        else:
            ax.plot(x[index_AIS],
                    y[index_AIS],
                    marker='x',
                    markersize=20,
                    color='blue')
            mea_axes(ax, style='axes')
            ax.spines['bottom'].set_color('blue')
            ax.spines['top'].set_color('blue')
            ax.spines['right'].set_color('blue')
            ax.spines['left'].set_color('blue')
            ax.tick_params(axis='x', colors='blue')
            ax.tick_params(axis='y', colors='blue')

        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="10%", pad=0.05)
        # for example neuron5.png use instead:
        # cax = divider.append_axes("right", size="5%", pad=0.05)

        norm = mpl.colors.Normalize(vmin=0, vmax=max_axon_delay)
        cbar = mpl.colorbar.ColorbarBase(cax,
                                         cmap=plt.cm.hsv,
                                         norm=norm,
                                         orientation='vertical')
        cbar.set_label(r'$\mathsf{\tau_{axon}\ [ms]}$', fontsize=14)

        longfigurename = "neuron%0d" % neuron
        show_or_savefig(subfolderpath, longfigurename)
        # for example neuron5.png use instead:
        # show_or_savefig(subfolderpath, longfigurename, dpi = 72)

        print("Plotted neuron %d" % neuron)

        plt.close()
def make_figure(figurename, figpath=None):

    colormap = plt.cm.hsv

    # Get traces
    V, t, x, y, trigger, neuron = AxonExperiment(GROUND_TRUTH_CULTURE).traces(
        GROUND_TRUTH_NEURON)
    if trigger < 0:  # may added to load_traces with trigger>-1 as condition
        trigger = find_AIS(V)

    t *= 1000  # convert to ms

    # AIS coordinates
    index_AIS = find_AIS(V)
    x_AIS = x[index_AIS]
    y_AIS = y[index_AIS]

    # Segmentation according Bakkum
    axon_Bakkum = dict()
    for pnr in (2, 2.25, 2.5, 2.75, 3, 3.25, 3.5, 3.75, 4, 4.25, 4.5, 4.75, 5):
        delay, _, _, _, axon = segment_axon_Bakkum(V, t, pnr_threshold=pnr)
        axon_Bakkum[pnr] = axon
    delay_Bakkum = delay
    Vmin_Bakkum = np.min(V, axis=1)

    # Segmentation according Bullmann
    from hana.grid import HidensTransformation
    axon_Bullmann = dict()
    delay_Bullmann = dict()
    Vmin_Bullmann = dict()
    x_Bullmann = dict()
    y_Bullmann = dict()
    hidens = HidensTransformation(x, y)
    for period in (1, 2, 3):
        if period > 1:
            xs, ys, Vs = hidens.subset(V, period=period, ioffset=0, joffset=1)
        else:
            xs, ys, Vs = x, y, V
        neighbors = neighbors_from_electrode_positions(xs,
                                                       ys,
                                                       neighborhood_radius=20 *
                                                       period)
        delay, _, std_delay, _, thr, _, _, _, axon = segment_axon_verbose(
            t, Vs, neighbors)
        if period == 1:
            keep_thr = thr
        else:
            axon = std_delay < keep_thr  # using the threshold, because less data to compute histogram
        axon_Bullmann[period] = axon
        delay_Bullmann[period] = delay
        Vmin_Bullmann[period] = np.min(Vs, axis=1)
        x_Bullmann[period] = xs
        y_Bullmann[period] = ys

    # Plotting
    fig = plt.figure(figurename, figsize=(13, 9))
    if not figpath:
        fig.suptitle(
            figurename +
            ' Haussdorf distance from ground truth for neuron %d' % neuron,
            fontsize=14,
            fontweight='bold')
    plt.subplots_adjust(left=0.10, right=0.95, top=0.90, bottom=0.05)

    bbox = None
    if neuron == 1544:
        bbox = [200, 850, 1200, 1720]
    V2size = lambda x: np.abs(x) * 2

    # Map axons for Bakkum's method, high threshold
    ax1 = plt.subplot(331)
    plot_image_axon_delay_voltage(ax1,
                                  AxonExperiment(GROUND_TRUTH_CULTURE).images(
                                      GROUND_TRUTH_NEURON, type='axon'),
                                  axon_Bakkum[5],
                                  delay_Bakkum,
                                  Vmin_Bakkum,
                                  x,
                                  y,
                                  transform=V2size)
    cross_hair(ax1, x_AIS, y_AIS, color='red')
    mea_axes(ax1, bbox=bbox, barposition='inside')
    ax1.set_title('Method I')
    plt.text(0.0,
             0.9,
             r'$\mathsf{V_n>5\sigma_{V}}$',
             ha='left',
             va='center',
             transform=ax1.transAxes)
    plt.title('a', loc='left', fontsize=18)

    # Map axons for Bullmann's method, grid spacing ~ 20um
    ax2 = plt.subplot(3, 3, 2)
    ax2h = plot_image_axon_delay_voltage(
        ax2,
        AxonExperiment(GROUND_TRUTH_CULTURE).images(GROUND_TRUTH_NEURON,
                                                    type='axon'),
        axon_Bullmann[1],
        delay_Bullmann[1],
        Vmin_Bullmann[1],
        x_Bullmann[1],
        y_Bullmann[1],
        transform=V2size)
    cross_hair(ax2, x_AIS, y_AIS, color='red')
    mea_axes(ax2, bbox=bbox, barposition='inside')
    ax2.set_title('Method II')
    plt.text(0.0,
             0.9,
             r'$\mathsf{r=18\ \mu m}$',
             ha='left',
             va='center',
             transform=ax2.transAxes)
    plt.title('b', loc='left', fontsize=18)

    # Ground truth =====================================================================
    ax3 = plt.subplot(1, 3, 3)
    from figure_footprint import plot_traces
    # Plot traces over high res background images
    images = AxonExperiment(GROUND_TRUTH_CULTURE).images(GROUND_TRUTH_NEURON,
                                                         type='enhanced')
    images.plot(alpha=1.0)
    plot_traces(ax3,
                x,
                y,
                axon_Bullmann[1],
                delay_Bullmann[1],
                t,
                V,
                max_axon_delay=2.5,
                background_color='none')
    cross_hair(ax2, x_AIS, y_AIS, color='red')
    adjust_position(ax3, yshift=0.21)
    mea_axes(ax3, bbox=[410, 740, 1200, 1620], barposition='outside')
    ax3.set_title('Groundtruth')
    plt.title('c', loc='left', fontsize=18)

    # Map axons for Bakkum's method, low threshold
    ax4 = plt.subplot(334)
    plot_image_axon_delay_voltage(ax4,
                                  AxonExperiment(GROUND_TRUTH_CULTURE).images(
                                      GROUND_TRUTH_NEURON, type='axon'),
                                  axon_Bakkum[3],
                                  delay_Bakkum,
                                  Vmin_Bakkum,
                                  x,
                                  y,
                                  transform=V2size)
    cross_hair(ax4, x_AIS, y_AIS, color='red')
    mea_axes(ax4, bbox=bbox, barposition='inside')
    plt.text(0.0,
             0.9,
             r'$\mathsf{V_n>3\sigma_{V}}$',
             ha='left',
             va='center',
             transform=ax4.transAxes)
    plt.title('d', loc='left', fontsize=18)

    # Map axons for Bullmann's method, grid spacing ~ 40um
    ax5 = plt.subplot(335)
    plot_image_axon_delay_voltage(ax5,
                                  AxonExperiment(GROUND_TRUTH_CULTURE).images(
                                      GROUND_TRUTH_NEURON, type='axon'),
                                  axon_Bullmann[2],
                                  delay_Bullmann[2],
                                  Vmin_Bullmann[2],
                                  x_Bullmann[2],
                                  y_Bullmann[2],
                                  transform=V2size)
    cross_hair(ax5, x_AIS, y_AIS, color='red')
    mea_axes(ax5, bbox=bbox, barposition='inside')
    plt.text(0.0,
             0.9,
             r'$\mathsf{r=36\ \mu m}$',
             ha='left',
             va='center',
             transform=ax5.transAxes)
    plt.title('e', loc='left', fontsize=18)

    # # Colorbar and Size legend for A, B, D, E
    # ax6 = plt.subplot(336)
    # for V in [1, 3, 10, 30, 100]:
    #     plt.scatter([],[],s=V2size(V), color='gray', edgecolor='none', label='%d' % V)
    # leg = plt.legend(loc=2, scatterpoints=1, frameon=False, title = r'$\mathsf{V_n\ [\mu V]}\ \ \ \ \ $')
    # leg.get_title().set_fontsize(14)
    # plt.axis('off')
    # adjust_position(ax6,xshrink=0.05,yshrink=0.02,xshift=-0.04)
    # divider = make_axes_locatable(ax6)
    # cax = divider.append_axes("right", size="10%", pad=0.05)
    #
    # norm = mpl.colors.Normalize(vmin=0, vmax=2)
    # cbar = mpl.colorbar.ColorbarBase(cax,
    #                                  cmap=plt.cm.summer,
    #                                  norm=norm,
    #                                  orientation='vertical')
    # cbar.set_label(r'$\mathsf{\tau_{axon}\ [ms]}$', fontsize=14)

    # Reading groundtruth xg, yg from the axon label file(s)
    xg, yg = AxonExperiment(GROUND_TRUTH_CULTURE).images(GROUND_TRUTH_NEURON,
                                                         type='axon').truth()

    # Bakkum's method: Haussdorf distance vs. threshold
    ax7 = plt.subplot(337)
    xx = list()
    yy = list()
    for pnr in np.sort(axon_Bakkum.keys()):
        xx.append(pnr)
        yy.append(
            compare_with_groundtruth(x[axon_Bakkum[pnr]], y[axon_Bakkum[pnr]],
                                     xg, yg))
    plt.plot(xx, yy, 'ko-')
    plt.xlabel(r'$\mathsf{V_{thr}\ [\sigma_{V}]}$')
    plt.ylabel(r'$\mathsf{H\ [\mu m]}$')
    plt.ylim((0, 400))
    plt.xlim((6, 1))
    adjust_position(ax7, xshrink=0.01, yshrink=0.01)
    without_spines_and_ticks(ax7)
    plt.title('f', loc='left', fontsize=18)

    # Bullmann's method: Haussdorf distance vs. spacing of electrodes in the hexagonal grid
    ax8 = plt.subplot(338)
    xx = list()
    yy = list()
    for period in axon_Bullmann.keys():
        xx.append(period * 18)
        yy.append(
            compare_with_groundtruth(x_Bullmann[period][axon_Bullmann[period]],
                                     y_Bullmann[period][axon_Bullmann[period]],
                                     xg, yg))
    plt.plot(xx, yy, 'ko--')
    plt.xlabel(r'$\mathsf{r\ [\mu m]}$')
    plt.ylabel(r'$\mathsf{H\ [\mu m]}$')
    plt.ylim((0, 400))
    plt.xlim((0, 80))
    adjust_position(ax8, xshrink=0.01, yshrink=0.01)
    without_spines_and_ticks(ax8)
    plt.title('g', loc='left', fontsize=18)

    ax9 = plt.subplot(5, 3, 15)
    img = plt.imread('larger_neighborhoods.png')
    plt.imshow(img)
    plt.axis('off')
    plt.title('h', loc='left', fontsize=18)
    adjust_position(ax9, xshift=-0.015, yshift=-0.011)

    show_or_savefig(figpath, figurename)
def make_figure(figurename, figpath=None):

    # Load electrode coordinates
    neighbors = electrode_neighborhoods(mea='hidens')

    # Load example data
    V, t, x, y, trigger, neuron = Experiment(FIGURE_CULTURE).traces(
        FIGURE_NEURON)
    t *= 1000  # convert to ms

    # Verbose dendrite segmentation function
    delay, mean_delay, std_delay, expected_std_delay, thr, valid_delay, index_AIS, min_delay, max_delay, \
        return_current_delay, dendrite = segment_dendrite_verbose(t, V, neighbors)

    # Making figure
    fig = plt.figure(figurename, figsize=(13, 10))
    if not figpath:
        fig.suptitle(
            figurename +
            ' Segmentation of the dendrite based on positive peak at neighboring electrodes',
            fontsize=14,
            fontweight='bold')
    plt.subplots_adjust(left=0.1, right=0.95, top=0.90, bottom=0.05)

    # Position of the AIS
    x_AIS = x[index_AIS]
    y_AIS = y[index_AIS]

    # subplot original unaligned traces
    ax1 = plt.subplot(231)
    V_AIS = V[index_AIS]  # Showing AIS trace in different color
    V_dendrites = V[np.where(
        dendrite)]  # Showing dendrite trace in different color
    ax1.plot(t, V.T, '-', color='gray', label='all')
    ax1.plot(t, V_dendrites.T, '-', color='black', label='dendrite')
    ax1.plot(t, V_AIS, 'r-', label='AIS')
    annotate_x_bar(half_peak_domain(t, V_AIS),
                   150,
                   text=' $|\delta_h$| = %0.3f ms' % half_peak_width(t, V_AIS))
    legend_without_multiple_labels(ax1, loc=4, frameon=False)
    ax1.set_ylim((-600, 200))
    ax1.set_ylabel(r'V [$\mu$V]')
    ax1.set_xlim((-1, 1))
    ax1.set_xlabel(r'$\Delta$t [ms]')
    without_spines_and_ticks(ax1)
    plt.title('a', loc='left', fontsize=18)

    # subplot std_delay map
    ax2 = plt.subplot(232)
    h1 = ax2.scatter(x,
                     y,
                     c=std_delay,
                     s=10,
                     marker='o',
                     edgecolor='None',
                     cmap='gray')
    h2 = plt.colorbar(h1, boundaries=np.linspace(0, 4, num=256))
    h2.set_label(r'$s_{\tau}$ [ms]')
    h2.set_ticks(np.arange(0, 4.5, step=0.5))
    cross_hair(ax2, x_AIS, y_AIS)
    mea_axes(ax2)
    plt.title('b', loc='left', fontsize=18)

    # subplot std_delay histogram
    ax3 = plt.subplot(233)
    ax3.hist(std_delay,
             bins=np.arange(0, max(delay), step=DELAY_EPSILON),
             facecolor='gray',
             edgecolor='gray',
             label='nothing')
    ax3.hist(std_delay,
             bins=np.arange(0, thr, step=DELAY_EPSILON),
             facecolor='k',
             edgecolor='k',
             label='axon/dendrite')
    ax3.scatter(expected_std_delay,
                25,
                marker='v',
                s=100,
                edgecolor='black',
                facecolor='gray',
                zorder=10)
    ax3.text(expected_std_delay,
             30,
             r'$\frac{8}{\sqrt{12}}$ ms',
             horizontalalignment='center',
             verticalalignment='bottom',
             zorder=10)
    ax3.legend(frameon=False)
    ax3.vlines(0, 0, 180, color='k', linestyles=':')
    ax3.set_ylim((0, 600))
    ax3.set_xlim((0, 4))
    ax3.set_ylabel(r'count')
    ax3.set_xlabel(r'$s_{\tau}$ [ms]')
    without_spines_and_ticks(ax3)
    adjust_position(ax3, xshrink=0.02)
    plt.title('c', loc='left', fontsize=18)

    # -------------- second row

    # plot map of delay within half peak domain == return_current_delay
    ax4 = plt.subplot(234)
    ax4.scatter(x,
                y,
                c=return_current_delay,
                s=10,
                marker='o',
                edgecolor='None',
                cmap='gray_r')
    cross_hair(ax4, x_AIS, y_AIS)
    ax4.text(300,
             300,
             r'$\tau \in \delta_h$',
             fontsize=18,
             bbox=dict(facecolor='white', pad=5, edgecolor='none'))
    mea_axes(ax4)
    plt.title('d', loc='left', fontsize=18)

    # plot map of thresholded std_delay
    ax5 = plt.subplot(235)
    ax5.scatter(x,
                y,
                c=valid_delay,
                s=10,
                marker='o',
                edgecolor='None',
                cmap='gray_r')
    ax5.text(300,
             300,
             r'$s_{\tau} < s_{min}$',
             fontsize=18,
             bbox=dict(facecolor='white', pad=5, edgecolor='none'))
    cross_hair(ax5, x_AIS, y_AIS)
    mea_axes(ax5)
    plt.title('e', loc='left', fontsize=18)

    # plot map of dendrite
    ax6 = plt.subplot(236)
    ax6.scatter(x,
                y,
                c=dendrite,
                s=10,
                marker='o',
                edgecolor='None',
                cmap='gray_r')
    ax6.text(300,
             300,
             'dendrite',
             fontsize=14,
             bbox=dict(facecolor='white', pad=5, edgecolor='none'))
    cross_hair(ax6, x_AIS, y_AIS)
    mea_axes(ax6)
    plt.title('f', loc='left', fontsize=18)

    show_or_savefig(figpath, figurename)
def make_figure(figurename, figpath=None):

    V, t, x, y, trigger, neuron = AxonExperiment(FIGURE_CULTURE).traces(FIGURE_NEURON)
    t *= 1000  # convert to ms

    # Neighborhood from electrode positions
    neighbors = electrode_neighborhoods(mea='hidens', x=x, y=y)

    Model1 = ModelDiscriminatorBakkum()
    Model1.fit(t, V, pnr_threshold=5)
    Model1.predict()
    Model2 = ModelDiscriminatorBullmann()
    Model2.fit(t, V, neighbors)
    Model2.predict()

    evaluation = AxonExperiment(FIGURE_CULTURE).comparison_of_discriminators(FIGURE_NEURONS)

    # Plotting Frames A~E
    fig = plt.figure(figurename, figsize=(13, 10))
    if not figpath:
        fig.suptitle(figurename + ' Comparison of segmentation methods', fontsize=14, fontweight='bold')
    plt.subplots_adjust(left=0.1, right=0.95, top=0.90, bottom=0.05)

    ax1 = plt.subplot(231)
    Model1.plot(ax1, xlabel=r'$\log_{10}(V_{n}/\sigma_{V})$', fontsize=14)
    adjust_position(ax1, xshrink=0.01)
    ax1.text(-0.3,450, 'Method I', size=14)
    ax1.set_ylim((0,500))
    without_spines_and_ticks(ax1)
    ax1.annotate('(fixed) threshold \n$%d\sigma_{V}$' % np.power(10, Model1.threshold),
                 xy=(Model1.threshold, 0),
                 xytext=(Model1.threshold, 200),
                 arrowprops=dict(facecolor='black', width=1),
                 size=14)
    plt.title('a', loc='left', fontsize=18)

    ax2 = plt.subplot(232)
    Model2.plot(ax2, xlabel=r'$\frac{s_{\tau}}{T/2}$', fontsize=20)
    adjust_position(ax2, xshrink=0.01)
    ax2.text(0.1,450, 'Method II', size=14)
    ax2.set_ylim((0,500))
    without_spines_and_ticks(ax2)
    ax2.annotate('(adaptive) threshold \n$s_{min}=%1.3f$ms' % Model2.threshold,
                 xy=(Model2.threshold, 0),
                 xytext=(Model2.threshold, 200),
                 arrowprops=dict(facecolor='black', width=1),
                 size=14)
    plt.title('b', loc='left', fontsize=18)

    ax3 = plt.subplot(233)
    Model1.plot_ROC(ax3, color='blue', marker='d', label = 'I')
    Model2.plot_ROC(ax3, color='black', marker='o', label = 'II')
    without_spines_and_ticks(ax3)
    ax3.plot((0,1),(0,1), 'k--', label ='chance')
    ax3.set_xlim((0,1))
    ax3.set_ylim((0,1))
    ax3.legend(loc=4, scatterpoints=1, frameon=False)
    plt.title('c', loc='left', fontsize=18)

    ax4 = plt.subplot(234)
    Model1.plot_Map(ax4, x, y)
    ax4.text(300, 300, r'I: $V_{n} > %d\sigma_{V}; \tau > \tau_{AIS}$' % np.power(10, Model1.threshold),
            bbox=dict(facecolor='white', pad=5, edgecolor='none'), size=14)
    mea_axes(ax4)
    plt.title('d', loc='left', fontsize=18)

    ax5 = plt.subplot(235)
    Model2.plot_Map(ax5, x, y)
    ax5.text(300, 300, r'II: $s_{\tau} < s_{min}; \tau > \tau_{AIS}$', bbox=dict(facecolor='white', pad=5, edgecolor='none'), size=14)
    mea_axes(ax5)
    plt.title('e', loc='left', fontsize=18)

    # Plotting Evaluation
    ax6 =plt.subplot(2,9,16)
    plot_pairwise_comparison(ax6, evaluation, 'AUC', ylim=(0, 0.5), legend=False)
    adjust_position(ax6, yshrink = 0.05)
    plt.title('f', loc='left', fontsize=18)
    ax6b =plt.subplot(2,9,17)
    plot_pairwise_comparison(ax6b, evaluation, 'TPR', ylim=(0, 1), legend=False)
    adjust_position(ax6b, xshift = 0.01, yshrink = 0.05)
    plt.title('g', loc='left', fontsize=18)
    ax6c =plt.subplot(2,9,18)
    plot_pairwise_comparison(ax6c, evaluation, 'FPR', ylim=(0, 0.02), legend=False)
    adjust_position(ax6c, xshift = 0.02, yshrink = 0.05)
    plt.title('h', loc='left', fontsize=18)

    show_or_savefig(figpath, figurename)
def make_figure(figurename, figpath=None):

    # Load electrode coordinates
    neighbors = electrode_neighborhoods(mea='hidens')

    # Load example data
    V, t, x, y, trigger, neuron = AxonExperiment(FIGURE_CULTURE).traces(
        FIGURE_NEURON)
    t *= 1000  # convert to ms

    # Load background images
    images = AxonExperiment(FIGURE_CULTURE).images(FIGURE_NEURON, type='axon')

    # Verbose axon segmentation function
    delay, mean_delay, std_delay, expected_std_delay, thr, valid_delay, index_AIS, positive_delay, axon \
        = segment_axon_verbose(t, V, neighbors)

    # Plot figure
    fig = plt.figure(figurename, figsize=(13, 7))

    # Map activity
    triggers, AIS, delays, positive_peak = AxonExperiment(
        FIGURE_CULTURE).compartments()
    map_data = AxonExperiment(FIGURE_CULTURE).event_map()
    ax1 = plt.subplot(121)
    ax1.scatter(
        map_data['x'],
        map_data['y'],
        # s=10,
        s=0.75 * np.sqrt(map_data['count']),
        c=-map_data['median_neg_peak'],
        marker='o',
        edgecolor='none',
        cmap=plt.cm.Blues,
        vmin=0,
        vmax=100,
        alpha=1)
    # trigger_indicies = np.unique(triggers.values()).astype(np.int16)-1
    # ax1.scatter(x[trigger_indicies],y[trigger_indicies], 10, color='red', marker='x')
    # trigger_indicies = Experiment(FIGURE_CULTURE).fixed_electrodes()['el']-1
    # ax1.scatter(x[trigger_indicies], y[trigger_indicies], 10, color='green', marker='+')
    print(max(map_data['count']))
    print(min(map_data['median_neg_peak']))
    # cross_hair(ax1, x[index_AIS], y[index_AIS], color='red')
    mea_axes(ax1)

    # Map axons for Bullmann's method
    ax2 = plt.subplot(122)
    max_axon_delay = np.around(np.nanmax(
        restrict_to_compartment(mean_delay, axon)),
                               decimals=1)
    V2size = lambda x: np.sqrt(np.abs(x)) * 5
    images.plot(alpha=0.5)
    radius = V2size(V)
    ax2.scatter(x[axon],
                y[axon],
                s=radius[axon],
                c=delay[axon],
                marker='o',
                edgecolor='none',
                cmap=plt.cm.hsv,
                vmin=0,
                vmax=max_axon_delay,
                alpha=1)

    # cross_hair(ax2, x[index_AIS], y[index_AIS], color='red')
    mea_axes(ax2)

    # # Colorbar and Size legend for A, B, D, E
    # ax6 = plt.subplot(322)
    # for legend_V in [1, 3, 10, 30, 100]:
    #     plt.scatter([], [], s=V2size(legend_V), color='gray', edgecolor='none', label='%d' % legend_V)
    # leg = plt.legend(loc=2, scatterpoints=1, frameon=False, title=r'$\mathsf{V_n\ [\mu V]}\ \ \ \ \ $')
    # leg.get_title().set_fontsize(14)
    # plt.axis('off')
    # adjust_position(ax6, xshrink=0.05, yshrink=0.02, xshift=-0.04)
    # divider = make_axes_locatable(ax6)
    # cax = divider.append_axes("right", size="10%", pad=0.05)
    #
    # norm = mpl.colors.Normalize(vmin=0, vmax=max_axon_delay)
    # cbar = mpl.colorbar.ColorbarBase(cax,
    #                                  cmap=plt.cm.hsv,
    #                                  norm=norm,
    #                                  orientation='vertical')
    # cbar.set_label(r'$\mathsf{\tau_{axon}\ [ms]}$', fontsize=14)

    show_or_savefig(figpath, figurename)
    plt.close()

    # Plot traces over high res background images
    images = AxonExperiment(FIGURE_CULTURE).images(FIGURE_NEURON,
                                                   type='axonhires')
    fig = plt.figure(figurename, figsize=(13, 13))
    ax = plt.subplot(111)
    images.plot(alpha=0.5)
    plot_traces(ax, x, y, axon, delay, t, V, max_axon_delay)
    mea_axes(ax)

    show_or_savefig(figpath, figurename + "_full_arbor", dpi=1200)
    plt.close()
Exemple #11
0
def make_figure(figurename, figpath=None):

    # Load electrode coordinates
    neighbors = electrode_neighborhoods(mea='hidens')

    # Load example data
    V, t, x, y, trigger, neuron = AxonExperiment(FIGURE_CULTURE).traces(
        FIGURE_NEURON)
    t *= 1000  # convert to ms

    # Verbose axon segmentation function
    delay, mean_delay, std_delay, expected_std_delay, thr, valid_delay, index_AIS, positive_delay, axon \
        = segment_axon_verbose(t, V, neighbors)

    logging.info('Axonal delays:')
    logging.info(restrict_to_compartment(mean_delay, axon))

    # Making figure
    fig = plt.figure(figurename, figsize=(13, 13))
    if not figpath:
        fig.suptitle(
            figurename +
            ' Segmentation of the axon based on negative peak at neighboring electrodes',
            fontsize=14,
            fontweight='bold')
    plt.subplots_adjust(left=0.10, right=0.95, top=0.90, bottom=0.05)

    # Define examples
    background_color = 'green'
    index_background_example = 500
    indices_background = neighborhood(neighbors, index_background_example)
    foreground_color = 'blue'
    index_foreground_example = 8624
    indices_foreground = neighborhood(neighbors, index_foreground_example)

    # -------------- first row

    # subplot original unaligned traces
    ax1 = plt.subplot(331)
    V_AIS = V[index_AIS]  # Showing AIS trace in different color
    V_axons = V[np.where(axon)]  # Showing AIS trace in different color
    ax1.plot(t, V.T, '-', color='gray', label='all')
    ax1.plot(t, V_axons.T, '-', color='black', label='axons')
    ax1.plot(t, V_AIS, 'r-', label='AIS')
    ax1.scatter(delay[index_AIS],
                -550,
                marker='^',
                s=100,
                edgecolor='None',
                facecolor='red')
    plt.annotate('', (delay[index_AIS] + 2, 150), (delay[index_AIS], 150),
                 arrowprops={
                     'arrowstyle': '->',
                     'color': 'red',
                     'shrinkA': 0,
                     'shrinkB': 0
                 })
    annotate_x_bar(delay[index_AIS] + (0, 2),
                   150,
                   text=r'$\tau > \tau_{AIS}$',
                   arrowstyle='->')
    legend_without_multiple_labels(ax1, loc=4, frameon=False)
    ax1.set_xlim((-4, 4))
    ax1.set_ylabel(r'V [$\mu$V]')
    ax1.set_xlabel(r'$\Delta$t [ms]')
    without_spines_and_ticks(ax1)
    # label_subplot(ax1, 'A', xoffset=-0.04, yoffset=-0.015)
    plt.title('a', loc='left', fontsize=18)

    # subplot delay map
    ax2 = plt.subplot(332)
    h1 = ax2.scatter(x,
                     y,
                     c=delay,
                     s=10,
                     marker='o',
                     edgecolor='None',
                     cmap='gray')
    h2 = plt.colorbar(h1)
    h2.set_label(r'$\tau$ [ms]')
    h2.set_ticks(np.linspace(-4, 4, num=9))
    add_AIS_and_example_neighborhoods(ax2, x, y, index_AIS, indices_background,
                                      indices_foreground)
    mea_axes(ax2)
    # label_subplot(ax2, 'B', xoffset=-0.015, yoffset=-0.015)
    plt.title('b', loc='left', fontsize=18)

    # subplot histogram of delays
    ax3 = plt.subplot(333)
    ax3.hist(delay,
             bins=len(t),
             facecolor='gray',
             edgecolor='gray',
             label='measured')
    ax3.scatter(delay[index_AIS],
                10,
                marker='v',
                s=100,
                edgecolor='None',
                facecolor='red',
                zorder=10)
    ax3.hlines(len(x) / len(t),
               min(t),
               max(t),
               color='k',
               linestyles='--',
               label='uniform')
    ax3.legend(loc=2, frameon=False)
    ax3.set_ylim((0, 200))
    ax3.set_xlim((min(t), max(t)))
    ax3.set_ylabel(r'count')
    ax3.set_xlabel(r'$\tau$ [ms]')
    without_spines_and_ticks(ax3)
    adjust_position(ax3, xshrink=0.02)
    # label_subplot(ax3, 'C', xoffset=-0.04, yoffset=-0.015)
    plt.title('c', loc='left', fontsize=18)

    # ------------- second row

    # Subplot neighborhood with uncorrelated negative peaks
    ax4 = plt.subplot(637)
    plot_traces_and_delays(ax4,
                           V,
                           t,
                           delay,
                           indices_background,
                           offset=-2,
                           ylim=(-10, 5),
                           color=background_color,
                           label='no axon')
    ax4.text(-3.5,
             -7.5,
             r'$s_{\tau}$ = %0.3f ms' % std_delay[index_background_example],
             color=background_color)
    ax4.set_yticks([-10, -5, 0, 5])
    legend_without_multiple_labels(ax4, loc=4, frameon=False)
    # label_subplot(ax4, 'D', xoffset=-0.04, yoffset=-0.015)
    plt.title('d', loc='left', fontsize=18)

    # Subplot neighborhood with correlated negative peaks
    ax5 = fig.add_subplot(6, 3, 10)
    plot_traces_and_delays(ax5,
                           V,
                           t,
                           delay,
                           indices_foreground,
                           offset=-20,
                           ylim=(-30, 10),
                           color=foreground_color,
                           label='axon')
    ax5.text(-3.5,
             -22,
             r'$s_{\tau}$ = %0.3f ms' % std_delay[index_foreground_example],
             color=foreground_color)
    ax5.set_yticks([-30, -20, -10, 0, 10])
    legend_without_multiple_labels(ax5, loc=4, frameon=False)
    # label_subplot(ax5, 'E', xoffset=-0.04, yoffset=-0.015)
    plt.title('e', loc='left', fontsize=18)

    # subplot std_delay map
    ax6 = plt.subplot(335)
    h1 = ax6.scatter(x,
                     y,
                     c=std_delay,
                     s=10,
                     marker='o',
                     edgecolor='None',
                     cmap='gray')
    h2 = plt.colorbar(h1, boundaries=np.linspace(0, 4, num=256))
    h2.set_label(r'$s_{\tau}$ [ms]')
    h2.set_ticks(np.arange(0, 4.5, step=0.5))
    add_AIS_and_example_neighborhoods(ax6, x, y, index_AIS, indices_background,
                                      indices_foreground)
    mea_axes(ax6)
    # label_subplot(ax6, 'F', xoffset=-0.015, yoffset=-0.01)
    plt.title('f', loc='left', fontsize=18)

    # subplot std_delay histogram
    ax7 = plt.subplot(336)
    ax7.hist(std_delay,
             bins=np.arange(0, max(delay), step=DELAY_EPSILON),
             facecolor='gray',
             edgecolor='gray',
             label='no axons')
    ax7.hist(std_delay,
             bins=np.arange(0, thr, step=DELAY_EPSILON),
             facecolor='k',
             edgecolor='k',
             label='axons')
    ax7.scatter(std_delay[index_foreground_example],
                25,
                marker='v',
                s=100,
                edgecolor='None',
                facecolor=foreground_color,
                zorder=10)
    ax7.scatter(std_delay[index_background_example],
                25,
                marker='v',
                s=100,
                edgecolor='None',
                facecolor=background_color,
                zorder=10)
    ax7.scatter(expected_std_delay,
                25,
                marker='v',
                s=100,
                edgecolor='black',
                facecolor='gray',
                zorder=10)
    ax7.text(expected_std_delay,
             30,
             r'$\frac{8}{\sqrt{12}}$ ms',
             horizontalalignment='center',
             verticalalignment='bottom',
             zorder=10)
    ax7.legend(loc=2, frameon=False)
    ax7.vlines(0, 0, 180, color='k', linestyles=':')
    ax7.set_ylim((0, 600))
    ax7.set_xlim((0, 4))
    ax7.set_ylabel(r'count')
    ax7.set_xlabel(r'$s_{\tau}$ [ms]')
    without_spines_and_ticks(ax7)
    adjust_position(ax7, xshrink=0.02)
    # label_subplot(ax7, 'G', xoffset=-0.04, yoffset=-0.01)
    plt.title('g', loc='left', fontsize=18)

    # ------------- third row

    # plot map of delay greater delay of AIS == positive_delay
    ax8 = plt.subplot(337)
    ax8.scatter(x,
                y,
                c=positive_delay,
                s=10,
                marker='o',
                edgecolor='None',
                cmap='gray_r')
    add_AIS_and_example_neighborhoods(ax8, x, y, index_AIS, indices_background,
                                      indices_foreground)
    ax8.text(300,
             300,
             r'$\tau > \tau_{AIS}$',
             fontsize=18,
             bbox=dict(facecolor='white', pad=5, edgecolor='none'))
    mea_axes(ax8)
    adjust_position(ax8, yshrink=0.02)
    plt.title('h', loc='left', fontsize=18)

    # plot map of thresholded std_delay
    ax9 = plt.subplot(338)
    ax9.scatter(x,
                y,
                c=valid_delay,
                s=10,
                marker='o',
                edgecolor='None',
                cmap='gray_r')
    ax9.text(300,
             300,
             r'$s_{\tau} < s_{min}$',
             fontsize=18,
             bbox=dict(facecolor='white', pad=5, edgecolor='none'))
    add_AIS_and_example_neighborhoods(ax9, x, y, index_AIS, indices_background,
                                      indices_foreground)
    mea_axes(ax9)
    adjust_position(ax9, yshrink=0.02)
    plt.title('i', loc='left', fontsize=18)

    # plot map of axon
    ax10 = plt.subplot(339)
    ax10.scatter(x,
                 y,
                 c=axon,
                 s=10,
                 marker='o',
                 edgecolor='None',
                 cmap='gray_r')
    ax10.text(300,
              300,
              'axon',
              fontsize=18,
              bbox=dict(facecolor='white', pad=5, edgecolor='none'))
    add_AIS_and_example_neighborhoods(ax10, x, y, index_AIS,
                                      indices_background, indices_foreground)
    mea_axes(ax10)
    adjust_position(ax10, yshrink=0.02)
    plt.title('j', loc='left', fontsize=18)

    show_or_savefig(figpath, figurename)