def load_spike_times_spontaneous():
    bcs = iaf.get_continue_bcs(n=40)
    print bcs
    sim = bluepy.Simulation(bcs[0])
    gids = list(sim.get_circuit_target())
    df = load_spike_times(bcs, gids)
    return df
def spike_count_difference():
    n_include = 20

    bcs_0 = iaf.get_continue_bcs(params='')[:n_include]
    bcs_1 = iaf.get_change_bcs(params='y')[:n_include]
    bcs_2 = iaf.get_change_bcs(params='e')[:n_include]
    bcs_3 = iaf.get_change_bcs(params='abcd')[:n_include]
    bcs_4 = iaf.get_change_bcs(params='abcdy')[:n_include]
    bcs_list = [bcs_1, bcs_2, bcs_3, bcs_4]
    bins=np.linspace(0, 50, 11)

    differences = np.zeros((4, len(bcs_0), bins.size - 1))
    for i, bcs in enumerate(bcs_list):
        differences[i, :, :] = get_differences(bcs_0, bcs, bins=bins)

    means = differences.mean(axis=1)
    errs = np.apply_along_axis(iaf.mean_confidence_interval, 1, differences)

    fig, axs = plt.subplots(2)
    ax = axs[0]
    xs = bins[:-1] + (bins[1] - bins[0])/2.0
    ax.plot(xs, np.zeros(xs.size), color='red')
    ax.errorbar(xs, means[0], errs[0])
    ax.errorbar(xs + 0.2, means[1], errs[1])

    ax = axs[1]
    xs = bins[:-1] + (bins[1] - bins[0])/2.0
    ax.plot(xs, np.zeros(xs.size), color='red')
    ax.errorbar(xs, means[2], errs[2])
    ax.errorbar(xs + 0.2, means[3], errs[3])

    plt.savefig('figures/perturbation_fr.pdf')
def plot_count_variance():
    """

    :return:
    """
    circuit = bluepy.Simulation(iaf.get_continue_bcs(n=2)[0]).circuit
    df_neurons = circuit.v2.cells({Cell.HYPERCOLUMN: 2})

    fig, axs = plt.subplots(6, 4, figsize=(10, 12))
    mean_fr = []

    for i, n in enumerate([40, 20, 10, 4, 2, 1]):
        df_counts = get_spike_counts_spontaneous_binned_concatenated(np.linspace(0, 2000, n+1))

        df_counts_exc = df_counts[df_neurons['synapse_class'] == 'EXC']
        df_counts_inh = df_counts[df_neurons['synapse_class'] == 'INH']
        mean_fr.append(df_counts['mean'].loc[84815])
        ax = axs[0 + i, 0]
        ax.scatter(df_counts_exc['mean'], df_counts_exc['variance'], marker='.', color='red', s=3, rasterized=True)

        xs = np.linspace(0, df_counts_exc['mean'].max(), 1000)
        ax.plot(xs, xs, '--', color='black')
        ax.plot(xs, (xs % 1) * (1 - (xs % 1)), '-', color='black')
        ax.set_ylim([0, xs[-1]])

        ax = axs[0 + i, 2]
        ax.hist(df_counts_exc['ff'], bins=np.linspace(0, 2, 20), histtype='step', color='red')

        #ax.set_xlim([0, 10])

        ax = axs[0 + i, 1]
        ax.scatter(df_counts_inh['mean'], df_counts_inh['variance'], marker='.', color='blue', s=3, rasterized=True)
        xs = np.linspace(0, df_counts_inh['mean'].max(), 1000)
        ax.plot(xs, xs, '--', color='black')
        ax.plot(xs, (xs % 1) * (1 - (xs % 1)), '-', color='black')
        ax.set_ylim([0, xs[-1]])

        ax = axs[0 + i, 3]
        ax.hist(df_counts_inh['ff'], bins=np.linspace(0, 2, 20), histtype='step', color='blue')
        #ax.set_xlim([0, 80])
    print mean_fr
    for ax in axs[:, :2].flatten():
        ax.set_xlabel('Spike count')
        ax.set_ylabel('Variance')
    for ax in axs[:, 2:].flatten():
        ax.set_xlabel('Fano factor')
        ax.set_ylabel('Neurons')
    for k, ax in enumerate(axs[:, 0]):
        ax.set_title(['50 ms', '100 ms', '200 ms', '500 ms', '1000 ms', '2000 ms'][k])
    plt.tight_layout()
    plt.savefig('figures_poisson/spont_variance_poisson.pdf', dpi=300)
def plot_count_variance_exp_25_summary():
    bins = np.linspace(1000, 7000, 13)

    print bins
    circuit = bluepy.Simulation(iaf.get_continue_bcs(n=2)[0]).circuit
    # df_neurons = circuit.v2.cells({Cell.HYPERCOLUMN: 2})
    df_neurons = get_selected_L456_gids()

    fig, axs = plt.subplots(5, len(bins) - 1, figsize=(20, 6))
    for k, variable in enumerate([False, True]):
        df_counts_list = [get_spike_counts_evoked(t_start=bins[j], t_end=bins[j + 1],
                                                  variable=variable) for j in range(len(bins) - 1)]

        df_counts_exc_list = []
        for i, df_counts in enumerate(df_counts_list):
            df_counts_exc = df_counts.loc[df_neurons.index.unique()][df_neurons['synapse_class'] == 'EXC']
            df_counts_exc_list.append(df_counts_exc)
            df_counts_inh = df_counts.loc[df_neurons.index.unique()][df_neurons['synapse_class'] == 'INH']

            ax = axs[0 + k * 2, i]
            ax.scatter(df_counts_exc['mean'], df_counts_exc['variance'], marker='.', color='red', s=3, rasterized=True)
            xs = np.linspace(0, df_counts_exc['mean'].max(), 1000)
            ax.plot(xs, xs, '--', color='black')
            ax.plot(xs, (xs % 1) * (1 - (xs % 1)), '-', color='black')
            ax.set_xlim([0, xs.max()])
            ax.set_ylim([0, xs.max()])

            ax = axs[1 + k * 2, i]
            ax.scatter(df_counts_inh['mean'], df_counts_inh['variance'], marker='.', color='blue', s=3, rasterized=True)
            xs = np.linspace(0, df_counts_inh['mean'].max(), 1000)
            ax.plot(xs, xs, '--', color='black')
            ax.plot(xs, (xs % 1) * (1 - (xs % 1)), '-', color='black')
            ax.set_xlim([0, xs.max()])
            ax.set_ylim([0, xs.max()])
    df_counts_list_vpm = [get_spike_counts_vpm(t_start=bins[j], t_end=bins[j + 1]) for j in range(2, len(bins) - 1)]
    for i, df_counts in enumerate(df_counts_list_vpm):

        ax = axs[-1, i+2]
        ax.scatter(df_counts['mean'], df_counts['variance'], marker='.', color='green', s=3, rasterized=True)
        xs = np.linspace(0, df_counts['mean'].max(), 1000)
        ax.plot(xs, xs, '--', color='black')
        ax.plot(xs, (xs % 1) * (1 - (xs % 1)), '-', color='black')
        ax.set_xlim([0, xs.max()])
        ax.set_ylim([0, xs.max()])
    plt.savefig('figures_poisson/exp_25_variance_poisson_summary.pdf', dpi=300)
def compute_spike_counts(df, n=30, vpm=False):
    bcs = iaf.get_continue_bcs(n=2)
    sim = bluepy.Simulation(bcs[0])
    if not vpm:
        gids = np.sort(np.array(list(sim.get_circuit_target())))
    else:
        gids = np.arange(221042, 221042 + 310)

    spikes_df = df.drop(columns=['time'])
    counts_all = np.zeros((gids.size, n), dtype=np.float64)
    for i in range(n):
        x = spikes_df[spikes_df['trial'] == i]
        counts_all[:, i] = np.bincount(np.array(x.index).astype(int), minlength=gids.max()+1)[-gids.size:]
    means = counts_all.mean(axis=1)
    vars = np.var(counts_all, ddof=1, axis=1)
    ffs = vars/means
    ffs[means == 0] = 0
    #print means
    df_counts = pd.DataFrame({'mean':means, 'variance':vars, 'ff':ffs}, index=gids)
    return df_counts