Esempio n. 1
0
def plot_results(alpha_a_0s, Ks_alpha_a_0,
                 gamma_a_0s, Ks_gamma_a_0,
                 figdir="."):

    # Plot the number of inferred states as a function of params
    fig = create_figure((5,1.5))

    ax = create_axis_at_location(fig, 0.6, 0.5, 1.7, .8, transparent=True)
    plt.figtext(0.05/5, 1.25/1.5, "A")
    ax.boxplot(Ks_alpha_a_0, positions=np.arange(1,1+len(alpha_a_0s)),
               boxprops=dict(color=allcolors[1]),
               whiskerprops=dict(color=allcolors[0]),
               flierprops=dict(color=allcolors[1]))
    ax.set_xticklabels(alpha_a_0s)
    plt.xlim(0.5,4.5)
    plt.ylim(40,90)
    # plt.yticks(np.arange(0,101,20))
    ax.set_xlabel("$a_{\\alpha_0}$")
    ax.set_ylabel("Number of States")

    ax = create_axis_at_location(fig, 3.1, 0.5, 1.7, .8, transparent=True)
    plt.figtext(2.55/5, 1.25/1.5, "B")
    ax.boxplot(Ks_gamma_a_0, positions=np.arange(1,1+len(gamma_a_0s)),
               boxprops=dict(color=allcolors[1]),
               whiskerprops=dict(color=allcolors[0]),
               flierprops=dict(color=allcolors[1]))
    ax.set_xticklabels(gamma_a_0s)
    plt.xlim(0.5,4.5)
    plt.ylim(40,90)
    # plt.yticks(np.arange(0,101,20))
    ax.set_xlabel("$a_{\\gamma}$")
    ax.set_ylabel("Number of States")

    plt.savefig(os.path.join(figdir, "figure7.pdf"))
    plt.savefig(os.path.join(figdir, "figure7.png"))
Esempio n. 2
0
def plot_pred_ll_vs_time(models,
                         results,
                         burnin=0,
                         homog_ll=np.nan,
                         std_ll=np.nan,
                         nlin_ll=np.nan,
                         true_ll=np.nan,
                         baseline=0,
                         normalizer=1,
                         output_dir=".",
                         xlim=None,
                         ylim=None,
                         title=None):
    from hips.plotting.layout import create_figure, create_axis_at_location
    from hips.plotting.colormaps import harvard_colors

    # Make the ICML figure
    fig = create_figure((3, 2))
    ax = create_axis_at_location(fig, 0.7, 0.4, 2.25, 1.35)
    col = harvard_colors()
    ax.grid()

    t_start = 0
    t_stop = 0

    def standardize(x):
        return (x - baseline) / normalizer

    for i, (model, result) in enumerate(zip(models, results)):
        ax.plot(result.timestamps[burnin:],
                standardize(result.test_lls[burnin:]),
                lw=2,
                color=col[i],
                label=model)

        # Update time limits
        t_start = min(t_start, result.timestamps[burnin:].min())
        t_stop = max(t_stop, result.timestamps[burnin:].max())

    if xlim is not None:
        t_start = xlim[0]
        t_stop = xlim[1]

    # plt.legend(loc="outside right")

    # Plot baselines
    ax.plot([t_start, t_stop],
            standardize(homog_ll) * np.ones(2),
            lw=2,
            color='k',
            label="Homog")

    # Plot the standard Hawkes test ll
    ax.plot([t_start, t_stop],
            standardize(std_ll) * np.ones(2),
            lw=2,
            color=col[len(models)],
            label="Std.")

    # Plot the Nonlinear Hawkes test ll
    ax.plot([t_start, t_stop],
            standardize(nlin_ll) * np.ones(2),
            lw=2,
            ls='--',
            color=col[len(models) + 1],
            label="Nonlinear")

    # Plot the true ll
    ax.plot([t_start, t_stop],
            standardize(true_ll) * np.ones(2),
            '--k',
            lw=2,
            label="True")

    ax.set_xlabel("time [sec]")
    ax.set_ylabel("Pred. LL. [nats/event]")

    ax.set_xscale("log")
    if xlim is not None:
        ax.set_xlim(xlim)
    else:
        ax.set_xlim(t_start, t_stop)
    if ylim is not None:
        ax.set_ylim(ylim)

    if title is not None:
        ax.set_title(title)

    output_file = os.path.join(output_dir, "pred_ll_vs_time.pdf")
    fig.savefig(output_file)
    plt.show()
Esempio n. 3
0
def plot_locations(result, offset=0):
    ### Plot the sampled locations for a few neurons
    _, _, _, _, Ls = result
    Ls_rot = []
    for L in Ls:
        R = compute_optimal_rotation(L, pfs, scale=False)
        Ls_rot.append(L.dot(R))
    Ls_rot = np.array(Ls_rot)

    fig = create_figure(figsize=(1.4,2.9))
    ax = create_axis_at_location(fig, .3, 1.7, 1, 1)

    # toplot = np.random.choice(np.arange(K), size=4, replace=False)
    toplot = np.linspace(offset,K+offset, 4, endpoint=False).astype(np.int)
    print(toplot)
    wheel_cmap = gradient_cmap([colors[0], colors[3], colors[2], colors[1], colors[0]])
    plot_colors = [wheel_cmap((np.pi+pfs_th[node_perm[j]])/(2*np.pi)) for j in toplot]

    for i,k in enumerate(node_perm):
        # plt.text(pfs[k,0], pfs[k,1], "%d" % i)
        if i not in toplot:
            color = 0.8 * np.ones(3)

            plt.plot(pfs[k,0], pfs[k, 1], 'o',
                     markerfacecolor=color, markeredgecolor=color,
                     markersize=4 + 4 * pf_size[k],
                     alpha=1.0)

    for i,k in enumerate(node_perm):
        # plt.text(pfs[k,0], pfs[k,1], "%d" % i)
        if i in toplot:
            j = np.where(toplot==i)[0][0]
            color = plot_colors[j]

            plt.plot(pfs[k,0], pfs[k, 1], 'o',
                     markerfacecolor=color, markeredgecolor=color,
                     markersize=4 + 4 * pf_size[k])



    #     plt.gca().add_patch(Circle((0,0), radius=rad, ec='k', fc="none"))
    plt.title("True Place Fields")
    plt.xlim(-45,45)
    plt.xticks([-40, -20, 0, 20, 40])
    # plt.xlabel("$x$")
    plt.ylim(-45,45)
    plt.yticks([-40, -20, 0, 20, 40])
    # plt.ylabel("$y$")

    # Now plot the inferred locations
    # plt.subplot(212, aspect='equal')
    ax = create_axis_at_location(fig, .3, .2, 1, 1)
    for L in Ls_rot[::2]:
        for j in np.random.permutation(len(toplot)):
            k = node_perm[toplot][j]
            color = plot_colors[j]
            plt.plot(L[k,0], L[k,1], 'o',
                     markerfacecolor=color, markeredgecolor="none",
                     markersize=4, alpha=0.25)

    plt.title("Locations Samples")
    # plt.xlim(-30, 30)
    # plt.xticks([])
    # plt.ylim(-30, 30)
    # plt.yticks([])
    plt.xlim(-3, 3)
    plt.xticks([-2, 0, 2])
    plt.ylim(-3, 3)
    plt.yticks([-2, 0, 2])

    plt.savefig(os.path.join(results_dir, "locations_%d.pdf" % offset))
Esempio n. 4
0
def plot_mean_and_pca_locations(result):
    ### Plot the sampled locations for a few neurons
    _, _, _, _, Ls = result
    Ls_rot = []
    for L in Ls:
        R = compute_optimal_rotation(L, pfs, scale=False)
        Ls_rot.append(L.dot(R))
    Ls_rot = np.array(Ls_rot)
    Ls_mean = np.mean(Ls_rot, 0)

    # Bin the data
    from pyhawkes.utils.utils import convert_continuous_to_discrete
    S_dt = convert_continuous_to_discrete(S, C, 0.25, 0, T)

    # Smooth the data to get a firing rate
    from scipy.ndimage.filters import gaussian_filter1d
    S_smooth = np.array([gaussian_filter1d(s, 4) for s in S_dt.T]).T

    # Run pca to gte an embedding
    from sklearn.decomposition import PCA
    pca = PCA(n_components=2)
    pca.fit(S_smooth)
    Z = pca.components_.T

    # Rotate
    R = compute_optimal_rotation(Z, pfs, scale=False)
    Z = Z.dot(R)

    wheel_cmap = gradient_cmap([colors[0], colors[3], colors[2], colors[1], colors[0]])
    fig = create_figure(figsize=(1.4,2.9))
    # plt.subplot(211, aspect='equal')
    ax = create_axis_at_location(fig, .3, 1.7, 1, 1)


    for i,k in enumerate(node_perm):
        color = wheel_cmap((np.pi+pfs_th[k])/(2*np.pi))
        plt.plot(Ls_mean[k,0], Ls_mean[k, 1], 'o',
                 markerfacecolor=color, markeredgecolor=color,
                 markersize=4 + 4 * pf_size[k],
                 alpha=0.7)

    #     plt.gca().add_patch(Circle((0,0), radius=rad, ec='k', fc="none"))
    plt.title("Mean Locations")
    plt.xlim(-3, 3)
    plt.xticks([-2, 0, 2])
    plt.ylim(-3, 3)
    plt.yticks([-2, 0, 2])


    # plt.subplot(212, aspect='equal')
    ax = create_axis_at_location(fig, .3, .2, 1, 1)

    for i,k in enumerate(node_perm):
        color = wheel_cmap((np.pi+pfs_th[k])/(2*np.pi))
        plt.plot(Z[k,0], Z[k, 1], 'o',
                 markerfacecolor=color, markeredgecolor=color,
                 markersize=4 + 4 * pf_size[k],
                 alpha=0.7)

    #     plt.gca().add_patch(Circle((0,0), radius=rad, ec='k', fc="none"))
    plt.title("PCA Locations")
    plt.xlim(-.5, .5)
    # plt.xlabel("$x$")
    plt.xticks([-.4, 0, .4])
    plt.ylim(-.5, .5)
    # plt.ylabel("$y$")
    plt.yticks([-.4, 0, .4])

    # plt.tight_layout()
    plt.savefig(os.path.join(results_dir, "hipp_mean_pca_locations.pdf"))
    plt.show()
Esempio n. 5
0
def plot_mean_and_pca_locations(result):
    ### Plot the sampled locations for a few neurons
    _, _, _, _, Ls = result
    Ls_rot = []
    for L in Ls:
        R = compute_optimal_rotation(L, pfs, scale=False)
        Ls_rot.append(L.dot(R))
    Ls_rot = np.array(Ls_rot)
    Ls_mean = np.mean(Ls_rot, 0)

    # Bin the data
    from pyhawkes.utils.utils import convert_continuous_to_discrete
    S_dt = convert_continuous_to_discrete(S, C, 0.25, 0, T)

    # Smooth the data to get a firing rate
    from scipy.ndimage.filters import gaussian_filter1d
    S_smooth = np.array([gaussian_filter1d(s, 4) for s in S_dt.T]).T

    # Run pca to gte an embedding
    from sklearn.decomposition import PCA
    pca = PCA(n_components=2)
    pca.fit(S_smooth)
    Z = pca.components_.T

    # Rotate
    R = compute_optimal_rotation(Z, pfs, scale=False)
    Z = Z.dot(R)

    wheel_cmap = gradient_cmap([colors[0], colors[3], colors[2], colors[1], colors[0]])
    fig = create_figure(figsize=(1.4,2.9))
    # plt.subplot(211, aspect='equal')
    ax = create_axis_at_location(fig, .3, 1.7, 1, 1)


    for i,k in enumerate(node_perm):
        color = wheel_cmap((np.pi+pfs_th[k])/(2*np.pi))
        plt.plot(Ls_mean[k,0], Ls_mean[k, 1], 'o',
                 markerfacecolor=color, markeredgecolor=color,
                 markersize=4 + 4 * pf_size[k],
                 alpha=0.7)

    #     plt.gca().add_patch(Circle((0,0), radius=rad, ec='k', fc="none"))
    plt.title("Mean Locations")
    plt.xlim(-3, 3)
    plt.xticks([-2, 0, 2])
    plt.ylim(-3, 3)
    plt.yticks([-2, 0, 2])


    # plt.subplot(212, aspect='equal')
    ax = create_axis_at_location(fig, .3, .2, 1, 1)

    for i,k in enumerate(node_perm):
        color = wheel_cmap((np.pi+pfs_th[k])/(2*np.pi))
        plt.plot(Z[k,0], Z[k, 1], 'o',
                 markerfacecolor=color, markeredgecolor=color,
                 markersize=4 + 4 * pf_size[k],
                 alpha=0.7)

    #     plt.gca().add_patch(Circle((0,0), radius=rad, ec='k', fc="none"))
    plt.title("PCA Locations")
    plt.xlim(-.5, .5)
    # plt.xlabel("$x$")
    plt.xticks([-.4, 0, .4])
    plt.ylim(-.5, .5)
    # plt.ylabel("$y$")
    plt.yticks([-.4, 0, .4])

    # plt.tight_layout()
    plt.savefig(os.path.join(results_dir, "hipp_mean_pca_locations.pdf"))
    plt.show()
Esempio n. 6
0
def plot_results(result):
    lls, plls, Weffs, Ps, Ls = result

    ### Colored locations
    wheel_cmap = gradient_cmap([colors[0], colors[3], colors[2], colors[1], colors[0]])
    fig = create_figure(figsize=(1.8, 1.8))
    # ax = create_axis_at_location(fig, .1, .1, 1.5, 1.5, box=False)
    ax = create_axis_at_location(fig, .6, .4, 1.1, 1.1)

    for i,k in enumerate(node_perm):
        color = wheel_cmap((np.pi+pfs_th[k])/(2*np.pi))
        # alpha = pfs_rad[k] / 47
        alpha = 0.7
        ax.add_patch(Circle((pfs[k,0], pfs[k,1]),
                            radius=3+4*pf_size[k],
                            color=color, ec="none",
                            alpha=alpha)
                            )

    plt.title("True place fields")
    # ax.text(0, 45, "True Place Fields",
    #         horizontalalignment="center",
    #         fontdict=dict(size=9))
    plt.xlim(-45,45)
    plt.xticks([-40, -20, 0, 20, 40])
    plt.xlabel("$x$ [cm]")
    plt.ylim(-45,45)
    plt.yticks([-40, -20, 0, 20, 40])
    plt.ylabel("$y$ [cm]")
    plt.savefig(os.path.join(results_dir, "hipp_colored_locations.pdf"))


    # Plot the inferred weighted adjacency matrix
    fig = create_figure(figsize=(1.8, 1.8))
    ax = create_axis_at_location(fig, .4, .4, 1.1, 1.1)

    Weff = np.array(Weffs[N_samples//2:]).mean(0)
    Weff = Weff[np.ix_(node_perm, node_perm)]
    lim = Weff[(1-np.eye(K)).astype(np.bool)].max()
    im = ax.imshow(np.kron(Weff, np.ones((20,20))),
                   interpolation="none", cmap="Greys", vmax=lim)
    ax.set_xticks([])
    ax.set_yticks([])

    # node_colors = wheel_cmap()
    node_values = ((np.pi+pfs_th[node_perm])/(2*np.pi))[:,None] *np.ones((K,2))
    yax = create_axis_at_location(fig, .2, .4, .3, 1.1)
    remove_plot_labels(yax)
    yax.imshow(node_values, interpolation="none",
               cmap=wheel_cmap)
    yax.set_xticks([])
    yax.set_yticks([])
    yax.set_ylabel("pre")

    xax = create_axis_at_location(fig, .4, .2, 1.1, .3)
    remove_plot_labels(xax)
    xax.imshow(node_values.T, interpolation="none",
               cmap=wheel_cmap)
    xax.set_xticks([])
    xax.set_yticks([])
    xax.set_xlabel("post")

    cbax = create_axis_at_location(fig, 1.55, .4, .04, 1.1)
    plt.colorbar(im, cax=cbax, ticks=[0, .1, .2,  .3])
    cbax.tick_params(labelsize=8, pad=1)
    cbax.set_ticklabels=["0", ".1", ".2",  ".3"]

    ax.set_title("Inferred Weights")
    plt.savefig(os.path.join(results_dir, "hipp_W.pdf"))

    # # Plot the inferred connection probability
    # plt.figure()
    # plt.imshow(P, interpolation="none", cmap="Greys", vmin=0)
    # plt.colorbar()

        # Plot the inferred weighted adjacency matrix
    fig = create_figure(figsize=(1.8, 1.8))
    ax = create_axis_at_location(fig, .4, .4, 1.1, 1.1)

    P = np.array(Ps[N_samples//2:]).mean(0)
    P = P[np.ix_(node_perm, node_perm)]
    im = ax.imshow(np.kron(P, np.ones((20,20))),
                   interpolation="none", cmap="Greys", vmin=0, vmax=1)
    ax.set_xticks([])
    ax.set_yticks([])

    # node_colors = wheel_cmap()
    node_values = ((np.pi+pfs_th[node_perm])/(2*np.pi))[:,None] *np.ones((K,2))
    yax = create_axis_at_location(fig, .2, .4, .3, 1.1)
    remove_plot_labels(yax)
    yax.imshow(node_values, interpolation="none",
               cmap=wheel_cmap)
    yax.set_xticks([])
    yax.set_yticks([])
    yax.set_ylabel("pre")

    xax = create_axis_at_location(fig, .4, .2, 1.1, .3)
    remove_plot_labels(xax)
    xax.imshow(node_values.T, interpolation="none",
               cmap=wheel_cmap)
    xax.set_xticks([])
    xax.set_yticks([])
    xax.set_xlabel("post")

    cbax = create_axis_at_location(fig, 1.55, .4, .04, 1.1)
    plt.colorbar(im, cax=cbax, ticks=[0, .5, 1])
    cbax.tick_params(labelsize=8, pad=1)
    cbax.set_ticklabels=["0.0", "0.5",  "1.0"]

    ax.set_title("Inferred Probability")
    plt.savefig(os.path.join(results_dir, "hipp_P.pdf"))


    plt.show()
Esempio n. 7
0
def plot_results(result):
    lls, plls, Weffs, Ps, Ls = result

    ### Colored locations
    wheel_cmap = gradient_cmap([colors[0], colors[3], colors[2], colors[1], colors[0]])
    fig = create_figure(figsize=(1.8, 1.8))
    # ax = create_axis_at_location(fig, .1, .1, 1.5, 1.5, box=False)
    ax = create_axis_at_location(fig, .6, .4, 1.1, 1.1)

    for i,k in enumerate(node_perm):
        color = wheel_cmap((np.pi+pfs_th[k])/(2*np.pi))
        # alpha = pfs_rad[k] / 47
        alpha = 0.7
        ax.add_patch(Circle((pfs[k,0], pfs[k,1]),
                            radius=3+4*pf_size[k],
                            color=color, ec="none",
                            alpha=alpha)
                            )

    plt.title("True place fields")
    # ax.text(0, 45, "True Place Fields",
    #         horizontalalignment="center",
    #         fontdict=dict(size=9))
    plt.xlim(-45,45)
    plt.xticks([-40, -20, 0, 20, 40])
    plt.xlabel("$x$ [cm]")
    plt.ylim(-45,45)
    plt.yticks([-40, -20, 0, 20, 40])
    plt.ylabel("$y$ [cm]")
    plt.savefig(os.path.join(results_dir, "hipp_colored_locations.pdf"))


    # Plot the inferred weighted adjacency matrix
    fig = create_figure(figsize=(1.8, 1.8))
    ax = create_axis_at_location(fig, .4, .4, 1.1, 1.1)

    Weff = np.array(Weffs[N_samples//2:]).mean(0)
    Weff = Weff[np.ix_(node_perm, node_perm)]
    lim = Weff[(1-np.eye(K)).astype(np.bool)].max()
    im = ax.imshow(np.kron(Weff, np.ones((20,20))),
                   interpolation="none", cmap="Greys", vmax=lim)
    ax.set_xticks([])
    ax.set_yticks([])

    # node_colors = wheel_cmap()
    node_values = ((np.pi+pfs_th[node_perm])/(2*np.pi))[:,None] *np.ones((K,2))
    yax = create_axis_at_location(fig, .2, .4, .3, 1.1)
    remove_plot_labels(yax)
    yax.imshow(node_values, interpolation="none",
               cmap=wheel_cmap)
    yax.set_xticks([])
    yax.set_yticks([])
    yax.set_ylabel("pre")

    xax = create_axis_at_location(fig, .4, .2, 1.1, .3)
    remove_plot_labels(xax)
    xax.imshow(node_values.T, interpolation="none",
               cmap=wheel_cmap)
    xax.set_xticks([])
    xax.set_yticks([])
    xax.set_xlabel("post")

    cbax = create_axis_at_location(fig, 1.55, .4, .04, 1.1)
    plt.colorbar(im, cax=cbax, ticks=[0, .1, .2,  .3])
    cbax.tick_params(labelsize=8, pad=1)
    cbax.set_ticklabels=["0", ".1", ".2",  ".3"]

    ax.set_title("Inferred Weights")
    plt.savefig(os.path.join(results_dir, "hipp_W.pdf"))

    # # Plot the inferred connection probability
    # plt.figure()
    # plt.imshow(P, interpolation="none", cmap="Greys", vmin=0)
    # plt.colorbar()

        # Plot the inferred weighted adjacency matrix
    fig = create_figure(figsize=(1.8, 1.8))
    ax = create_axis_at_location(fig, .4, .4, 1.1, 1.1)

    P = np.array(Ps[N_samples//2:]).mean(0)
    P = P[np.ix_(node_perm, node_perm)]
    im = ax.imshow(np.kron(P, np.ones((20,20))),
                   interpolation="none", cmap="Greys", vmin=0, vmax=1)
    ax.set_xticks([])
    ax.set_yticks([])

    # node_colors = wheel_cmap()
    node_values = ((np.pi+pfs_th[node_perm])/(2*np.pi))[:,None] *np.ones((K,2))
    yax = create_axis_at_location(fig, .2, .4, .3, 1.1)
    remove_plot_labels(yax)
    yax.imshow(node_values, interpolation="none",
               cmap=wheel_cmap)
    yax.set_xticks([])
    yax.set_yticks([])
    yax.set_ylabel("pre")

    xax = create_axis_at_location(fig, .4, .2, 1.1, .3)
    remove_plot_labels(xax)
    xax.imshow(node_values.T, interpolation="none",
               cmap=wheel_cmap)
    xax.set_xticks([])
    xax.set_yticks([])
    xax.set_xlabel("post")

    cbax = create_axis_at_location(fig, 1.55, .4, .04, 1.1)
    plt.colorbar(im, cax=cbax, ticks=[0, .5, 1])
    cbax.tick_params(labelsize=8, pad=1)
    cbax.set_ticklabels=["0.0", "0.5",  "1.0"]

    ax.set_title("Inferred Probability")
    plt.savefig(os.path.join(results_dir, "hipp_P.pdf"))


    plt.show()
Esempio n. 8
0
def plot_locations(result, offset=0):
    ### Plot the sampled locations for a few neurons
    _, _, _, _, Ls = result
    Ls_rot = []
    for L in Ls:
        R = compute_optimal_rotation(L, pfs, scale=False)
        Ls_rot.append(L.dot(R))
    Ls_rot = np.array(Ls_rot)

    fig = create_figure(figsize=(1.4,2.9))
    ax = create_axis_at_location(fig, .3, 1.7, 1, 1)

    # toplot = np.random.choice(np.arange(K), size=4, replace=False)
    toplot = np.linspace(offset,K+offset, 4, endpoint=False).astype(np.int)
    print toplot
    wheel_cmap = gradient_cmap([colors[0], colors[3], colors[2], colors[1], colors[0]])
    plot_colors = [wheel_cmap((np.pi+pfs_th[node_perm[j]])/(2*np.pi)) for j in toplot]

    for i,k in enumerate(node_perm):
        # plt.text(pfs[k,0], pfs[k,1], "%d" % i)
        if i not in toplot:
            color = 0.8 * np.ones(3)

            plt.plot(pfs[k,0], pfs[k, 1], 'o',
                     markerfacecolor=color, markeredgecolor=color,
                     markersize=4 + 4 * pf_size[k],
                     alpha=1.0)

    for i,k in enumerate(node_perm):
        # plt.text(pfs[k,0], pfs[k,1], "%d" % i)
        if i in toplot:
            j = np.where(toplot==i)[0][0]
            color = plot_colors[j]

            plt.plot(pfs[k,0], pfs[k, 1], 'o',
                     markerfacecolor=color, markeredgecolor=color,
                     markersize=4 + 4 * pf_size[k])



    #     plt.gca().add_patch(Circle((0,0), radius=rad, ec='k', fc="none"))
    plt.title("True Place Fields")
    plt.xlim(-45,45)
    plt.xticks([-40, -20, 0, 20, 40])
    # plt.xlabel("$x$")
    plt.ylim(-45,45)
    plt.yticks([-40, -20, 0, 20, 40])
    # plt.ylabel("$y$")

    # Now plot the inferred locations
    # plt.subplot(212, aspect='equal')
    ax = create_axis_at_location(fig, .3, .2, 1, 1)
    for L in Ls_rot[::2]:
        for j in np.random.permutation(len(toplot)):
            k = node_perm[toplot][j]
            color = plot_colors[j]
            plt.plot(L[k,0], L[k,1], 'o',
                     markerfacecolor=color, markeredgecolor="none",
                     markersize=4, alpha=0.25)

    plt.title("Locations Samples")
    # plt.xlim(-30, 30)
    # plt.xticks([])
    # plt.ylim(-30, 30)
    # plt.yticks([])
    plt.xlim(-3, 3)
    plt.xticks([-2, 0, 2])
    plt.ylim(-3, 3)
    plt.yticks([-2, 0, 2])

    plt.savefig(os.path.join(results_dir, "locations_%d.pdf" % offset))
def plot_pred_ll_vs_time(models, results, burnin=0,
                         homog_ll=np.nan,
                         std_ll=np.nan,
                         nlin_ll=np.nan,
                         true_ll=np.nan,
                         baseline=0,
                         normalizer=1,
                         output_dir=".",
                         xlim=None, ylim=None,
                         title=None):
    from hips.plotting.layout import create_figure, create_axis_at_location
    from hips.plotting.colormaps import harvard_colors

    # Make the ICML figure
    fig = create_figure((3,2))
    ax = create_axis_at_location(fig, 0.7, 0.4, 2.25, 1.35)
    col = harvard_colors()
    ax.grid()

    t_start = 0
    t_stop = 0

    def standardize(x):
        return (x-baseline)/normalizer

    for i, (model, result) in enumerate(zip(models, results)):
        ax.plot(result.timestamps[burnin:],
                 standardize(result.test_lls[burnin:]),
                 lw=2, color=col[i], label=model)

        # Update time limits
        t_start = min(t_start, result.timestamps[burnin:].min())
        t_stop = max(t_stop, result.timestamps[burnin:].max())

    if xlim is not None:
        t_start = xlim[0]
        t_stop = xlim[1]

    # plt.legend(loc="outside right")

    # Plot baselines
    ax.plot([t_start, t_stop], standardize(homog_ll)*np.ones(2),
             lw=2, color='k', label="Homog")

    # Plot the standard Hawkes test ll
    ax.plot([t_start, t_stop], standardize(std_ll)*np.ones(2),
             lw=2, color=col[len(models)], label="Std.")

    # Plot the Nonlinear Hawkes test ll
    ax.plot([t_start, t_stop], standardize(nlin_ll)*np.ones(2),
             lw=2, ls='--', color=col[len(models)+1], label="Nonlinear")

    # Plot the true ll
    ax.plot([t_start, t_stop], standardize(true_ll)*np.ones(2),
             '--k',  lw=2,label="True")


    ax.set_xlabel("time [sec]")
    ax.set_ylabel("Pred. LL. [nats/event]")

    ax.set_xscale("log")
    if xlim is not None:
        ax.set_xlim(xlim)
    else:
        ax.set_xlim(t_start, t_stop)
    if ylim is not None:
        ax.set_ylim(ylim)

    if title is not None:
        ax.set_title(title)

    output_file = os.path.join(output_dir, "pred_ll_vs_time.pdf")
    fig.savefig(output_file)
    plt.show()
Esempio n. 10
0
def plot_census_results(train, samples, test, test_pis):
    # Extract samp[les
    train_mus = np.array([s[0] for s in samples])
    train_psis = np.array([s[1][0][0] for s in samples])
    # omegas = np.array([s[1][0][1] for s in samples])

    # Adjust psis by the mean and compute the inferred pis
    train_psis += train_mus[0][None,None,:]
    train_pis = np.array([psi_to_pi(psi_sample) for psi_sample in train_psis])
    train_pi_mean = np.mean(train_pis, axis=0)
    train_pi_std = np.std(train_pis, axis=0)

    # Compute test pi mean and std
    test_pi_mean = np.mean(test_pis, axis=0)
    test_pi_std = np.std(test_pis, axis=0)

    # Compute empirical probabilities
    train_pi_emp = train.data / train.data.sum(axis=1)[:,None]
    test_pi_emp = test.data / test.data.sum(axis=1)[:,None]


    # Plot the temporal trajectories for a few names
    names = ["Scott", "Matthew", "Ethan"]
    states = ["NY", "TX", "WA"]
    linestyles = ["-", "--", ":"]

    fig = create_figure(figsize=(3., 3))
    ax1 = create_axis_at_location(fig, 0.6, 0.5, 2.25, 1.75)
    for name, color in zip(names, colors):
        for state, linestyle in zip(states, linestyles):
            train_state_inds = (train.states == state)
            train_name_ind = np.array(train.names) == name.lower()
            train_years = train.years[train.states == state]
            train_mean_name = train_pi_mean[train_state_inds, train_name_ind]
            train_std_name = train_pi_std[train_state_inds, train_name_ind]

            test_state_inds = (test.states == state)
            test_name_ind = np.array(test.names) == name.lower()
            test_years = test.years[test.states == state]
            test_mean_name = test_pi_mean[test_state_inds, test_name_ind]
            test_std_name = test_pi_std[test_state_inds, test_name_ind]

            years = np.concatenate((train_years, test_years))
            mean_name = np.concatenate((train_mean_name, test_mean_name))
            std_name = np.concatenate((train_std_name, test_std_name))

            # Sausage plot
            sausage_plot(years, mean_name, std_name,
                         color=color, alpha=0.5)

            # Plot inferred mean
            plt.plot(years, mean_name,
                     color=color, label="%s, %s" % (name, state),
                     ls=linestyle, lw=2)

            # Plot empirical probabilities
            plt.plot(train.years[train_state_inds],
                     train_pi_emp[train_state_inds, train_name_ind],
                     color=color,
                     ls="", marker="x", markersize=4)

            plt.plot(test.years[test_state_inds],
                     test_pi_emp[test_state_inds, test_name_ind],
                     color=color,
                     ls="", marker="x", markersize=4)

    # Plot a vertical line to divide train and test
    ylim = plt.gca().get_ylim()
    plt.plot((test.years.min()-0.5) * np.ones(2), ylim, ':k', lw=0.5)
    plt.ylim(ylim)

    # plt.legend(loc="outside right")
    plt.legend(bbox_to_anchor=(0., 1.05, 1., .105), loc=3,
               ncol=len(names), mode="expand", borderaxespad=0.,
               fontsize="x-small")

    plt.xlabel("Year")
    plt.xlim(train.years.min(), test.years.max()+0.1)
    plt.ylabel("Probability")

    # plt.tight_layout()
    fig.savefig("census_gp_rates.pdf")

    plt.show()
    plt.pause(0.1)
Esempio n. 11
0
def draw_mixture_figure(Ns, Ss, z, lmbda, filename="figure1.png", saveargs=dict(dpi=300)):
    fig = create_figure((5.5, 2.7))
    ax = create_axis_at_location(fig, .75, .5, 4., 1.375)
    ymax = 105
    # Plot the rates
    for i in range(n):
        ax.add_patch(Rectangle([i*D,0], D, lmbda[z[i]],
                               color=colors[z[i]], ec="none", alpha=0.5))
        ax.plot([i*D, (i+1)*D], lmbda[z[i]] * np.ones(2), '-k', lw=2)

        if i < n-1:
            ax.plot([(i+1)*D, (i+1)*D], [lmbda[z[i]], lmbda[z[i+1]]], '-k', lw=2)
            
        # Plot boundaries
        ax.plot([(i+1)*D, (i+1)*D], [0, ymax], ':k', lw=1)
        
        
    # Plot x axis
    plt.plot([0,T], [0,0], '-k', lw=2)

    # Plot spike times
    for s in Ss:
        plt.plot([s,s], [0,60], '-ko', markerfacecolor='k', markersize=5)

    plt.xlabel("time [ms]")
    plt.ylabel("firing rate [Hz]")
    plt.xlim(0,T)
    plt.ylim(-5,ymax)

    ## Now plot the spike count above
    ax = create_axis_at_location(fig, .75, 2., 4., .25)
    for i in xrange(n):
        # Plot boundaries
        ax.plot([(i+1)*D, (i+1)*D], [0, 10], '-k', lw=1)
        ax.text(i*D + D/3.5, 3, "%d" % Ns[i], fontdict={"size":9})
    ax.set_xlim(0,T)
    ax.set_ylim(0,10)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.yaxis.labelpad = 30
    ax.set_ylabel("${s_t}$", rotation=0,  verticalalignment='center')

    ## Now plot the latent state above that above
    ax = create_axis_at_location(fig, .75, 2.375, 4., .25)
    for i in xrange(n):
        # Plot boundaries
        ax.add_patch(Rectangle([i*D,0], D, 10,
                            color=colors[z[i]], ec="none", alpha=0.5))

        ax.plot([(i+1)*D, (i+1)*D], [0, 10], '-k', lw=1)
        ax.text(i*D + D/3.5, 3, "u" if z[i]==0 else "d", fontdict={"size":9})
    ax.set_xlim(0,T)
    ax.set_ylim(0,10)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.yaxis.labelpad = 30
    ax.set_ylabel("${z_t}$", rotation=0,  verticalalignment='center')

    
    #fig.savefig(filename + ".pdf")
    fig.savefig(filename, **saveargs)

    plt.close(fig)
Esempio n. 12
0
def draw_mixture_figure(Ns,
                        Ss,
                        z,
                        lmbda,
                        filename="figure1.png",
                        saveargs=dict(dpi=300)):
    fig = create_figure((5.5, 2.7))
    ax = create_axis_at_location(fig, .75, .5, 4., 1.375)
    ymax = 105
    # Plot the rates
    for i in range(n):
        ax.add_patch(
            Rectangle([i * D, 0],
                      D,
                      lmbda[z[i]],
                      color=colors[z[i]],
                      ec="none",
                      alpha=0.5))
        ax.plot([i * D, (i + 1) * D], lmbda[z[i]] * np.ones(2), '-k', lw=2)

        if i < n - 1:
            ax.plot([(i + 1) * D, (i + 1) * D], [lmbda[z[i]], lmbda[z[i + 1]]],
                    '-k',
                    lw=2)

        # Plot boundaries
        ax.plot([(i + 1) * D, (i + 1) * D], [0, ymax], ':k', lw=1)

    # Plot x axis
    plt.plot([0, T], [0, 0], '-k', lw=2)

    # Plot spike times
    for s in Ss:
        plt.plot([s, s], [0, 60], '-ko', markerfacecolor='k', markersize=5)

    plt.xlabel("time [ms]")
    plt.ylabel("firing rate [Hz]")
    plt.xlim(0, T)
    plt.ylim(-5, ymax)

    ## Now plot the spike count above
    ax = create_axis_at_location(fig, .75, 2., 4., .25)
    for i in xrange(n):
        # Plot boundaries
        ax.plot([(i + 1) * D, (i + 1) * D], [0, 10], '-k', lw=1)
        ax.text(i * D + D / 3.5, 3, "%d" % Ns[i], fontdict={"size": 9})
    ax.set_xlim(0, T)
    ax.set_ylim(0, 10)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.yaxis.labelpad = 30
    ax.set_ylabel("${s_t}$", rotation=0, verticalalignment='center')

    ## Now plot the latent state above that above
    ax = create_axis_at_location(fig, .75, 2.375, 4., .25)
    for i in xrange(n):
        # Plot boundaries
        ax.add_patch(
            Rectangle([i * D, 0],
                      D,
                      10,
                      color=colors[z[i]],
                      ec="none",
                      alpha=0.5))

        ax.plot([(i + 1) * D, (i + 1) * D], [0, 10], '-k', lw=1)
        ax.text(i * D + D / 3.5,
                3,
                "u" if z[i] == 0 else "d",
                fontdict={"size": 9})
    ax.set_xlim(0, T)
    ax.set_ylim(0, 10)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.yaxis.labelpad = 30
    ax.set_ylabel("${z_t}$", rotation=0, verticalalignment='center')

    #fig.savefig(filename + ".pdf")
    fig.savefig(filename, **saveargs)

    plt.close(fig)
Esempio n. 13
0
def plot_census_results(train, samples, test, test_pis):
    # Extract samp[les
    train_mus = np.array([s[0] for s in samples])
    train_psis = np.array([s[1][0][0] for s in samples])
    # omegas = np.array([s[1][0][1] for s in samples])

    # Adjust psis by the mean and compute the inferred pis
    train_psis += train_mus[0][None,None,:]
    train_pis = np.array([psi_to_pi(psi_sample) for psi_sample in train_psis])
    train_pi_mean = np.mean(train_pis, axis=0)
    train_pi_std = np.std(train_pis, axis=0)

    # Compute test pi mean and std
    test_pi_mean = np.mean(test_pis, axis=0)
    test_pi_std = np.std(test_pis, axis=0)

    # Compute empirical probabilities
    train_pi_emp = train.data / train.data.sum(axis=1)[:,None]
    test_pi_emp = test.data / test.data.sum(axis=1)[:,None]


    # Plot the temporal trajectories for a few names
    names = ["Scott", "Matthew", "Ethan"]
    states = ["NY", "TX", "WA"]
    linestyles = ["-", "--", ":"]

    fig = create_figure(figsize=(3., 3))
    ax1 = create_axis_at_location(fig, 0.6, 0.5, 2.25, 1.75)
    for name, color in zip(names, colors):
        for state, linestyle in zip(states, linestyles):
            train_state_inds = (train.states == state)
            train_name_ind = np.array(train.names) == name.lower()
            train_years = train.years[train.states == state]
            train_mean_name = train_pi_mean[train_state_inds, train_name_ind]
            train_std_name = train_pi_std[train_state_inds, train_name_ind]

            test_state_inds = (test.states == state)
            test_name_ind = np.array(test.names) == name.lower()
            test_years = test.years[test.states == state]
            test_mean_name = test_pi_mean[test_state_inds, test_name_ind]
            test_std_name = test_pi_std[test_state_inds, test_name_ind]

            years = np.concatenate((train_years, test_years))
            mean_name = np.concatenate((train_mean_name, test_mean_name))
            std_name = np.concatenate((train_std_name, test_std_name))

            # Sausage plot
            sausage_plot(years, mean_name, std_name,
                         color=color, alpha=0.5)

            # Plot inferred mean
            plt.plot(years, mean_name,
                     color=color, label="%s, %s" % (name, state),
                     ls=linestyle, lw=2)

            # Plot empirical probabilities
            plt.plot(train.years[train_state_inds],
                     train_pi_emp[train_state_inds, train_name_ind],
                     color=color,
                     ls="", marker="x", markersize=4)

            plt.plot(test.years[test_state_inds],
                     test_pi_emp[test_state_inds, test_name_ind],
                     color=color,
                     ls="", marker="x", markersize=4)

    # Plot a vertical line to divide train and test
    ylim = plt.gca().get_ylim()
    plt.plot((test.years.min()-0.5) * np.ones(2), ylim, ':k', lw=0.5)
    plt.ylim(ylim)

    # plt.legend(loc="outside right")
    plt.legend(bbox_to_anchor=(0., 1.05, 1., .105), loc=3,
               ncol=len(names), mode="expand", borderaxespad=0.,
               fontsize="x-small")

    plt.xlabel("Year")
    plt.xlim(train.years.min(), test.years.max()+0.1)
    plt.ylabel("Probability")

    # plt.tight_layout()
    fig.savefig("census_gp_rates.pdf")

    plt.show()
    plt.pause(0.1)