Ejemplo n.º 1
0
def analyse_results(SM_BC,
                    RM_BC,
                    StateM_BC,
                    return_freq="ripple",
                    plot=False,
                    analyse_currents=False):
    """
    Analyses results from simulations (see `detect_oscillations.py`)
    :params SM_BC, RM_BC, StateM_BC: Brian2 spike and rate monitors of BC population (see `run_simulation()`)
    :param return_freq: str - "ripple" or "gamma" for frequency range to analyse
    :param plot: bool for plotting or not
    :param analyse_currents: bool for analysing currents or not
    :return: avg. ripple/gamma frequency and ripple/gamma power
    """

    assert return_freq in ["ripple", "gamma"]

    if SM_BC.num_spikes > 0:  # check if there is any activity
        spike_times_BC, spiking_neurons_BC, rate_BC = preprocess_monitors(
            SM_BC, RM_BC, calc_ISI=False)
        mean_rate_BC, rate_ac_BC, max_ac_BC, t_max_ac_BC, f_BC, Pxx_BC = analyse_rate(
            rate_BC, fs=1000., slice_idx=[])
        avg_ripple_freq_BC, ripple_power_BC = ripple(f_BC,
                                                     Pxx_BC,
                                                     slice_idx=[])
        avg_gamma_freq_BC, gamma_power_BC = gamma(f_BC, Pxx_BC, slice_idx=[])

        if analyse_currents:
            # simplified version of `../helper.py/_estimate_LFP()`
            t = StateM_BC.t_ * 1000.  # *1000 ms conversion
            v = StateM_BC[nBCs / 2].vm
            g_exc = StateM_BC[nBCs / 2].g_ampa * nS
            i_exc = g_exc * (v - (Erev_E * np.ones_like(v / mV)))  # pA
            g_inh = StateM_BC[nBCs / 2].g_gaba * nS
            i_inh = g_inh * (v - (Erev_I * np.ones_like(v / mV)))  # pA
        if plot:
            plot_PSD(rate_BC,
                     rate_ac_BC,
                     f_BC,
                     Pxx_BC,
                     "BC_population",
                     "green",
                     multiplier_=1)
            plot_zoomed(spike_times_BC,
                        spiking_neurons_BC,
                        rate_BC,
                        "BC_population",
                        "green",
                        multiplier_=1,
                        PC_pop=False,
                        StateM=StateM_BC)

        if return_freq == "ripple":
            return avg_ripple_freq_BC, ripple_power_BC
        elif return_freq == "gamma":
            return avg_gamma_freq_BC, gamma_power_BC
    else:
        print("No activity !")
        return np.nan, np.nan
Ejemplo n.º 2
0
def analyse_results(SM_PC,
                    SM_BC,
                    RM_PC,
                    RM_BC,
                    selection,
                    StateM_PC,
                    StateM_BC,
                    seed,
                    multiplier,
                    linear,
                    pklf_name,
                    dir_name,
                    analyse_replay=True,
                    TFR=True,
                    save=True,
                    verbose=True):
    """
    Analyses results from simulations (see `detect_oscillations.py`)
    :param SM_PC, SM_BC, RM_PC, RM_BC: Brian2 spike and rate monitors of PC and BC populations (see `run_simulation()`)
    :param selection: array of selected cells used by PC multi state monitor
    :param seed: random seed used to run the sim - here used only for saving
    :param multiplier: weight matrix multiplier (see `spw_network_wmx_mult.py`)
    :param linear: bool for linear/circular weight matrix (more advanced replay detection is used in linear case)
    :param pklf_name: file name of saved place fileds used for replay detection in the linear case
    :param dir_name: subdirectory name used to save replay detection (and optionally TFR) figures in linear case
    :param analyse_replay: bool for analysing replay or not
    :param TFR: bool for calculating time freq. repr. (using wavelet analysis) or not
    :param save: bool for saving results
    :param verbose: bool for printing results or not
    """

    if SM_PC.num_spikes > 0 and SM_BC.num_spikes > 0:  # check if there is any activity

        spike_times_PC, spiking_neurons_PC, rate_PC, ISI_hist_PC, bin_edges_PC = preprocess_monitors(
            SM_PC, RM_PC)
        spike_times_BC, spiking_neurons_BC, rate_BC = preprocess_monitors(
            SM_BC, RM_BC, calc_ISI=False)
        if not linear:
            plot_raster(spike_times_PC,
                        spiking_neurons_PC,
                        rate_PC, [ISI_hist_PC, bin_edges_PC],
                        None,
                        "blue",
                        multiplier_=multiplier)
        subset = plot_zoomed(spike_times_PC,
                             spiking_neurons_PC,
                             rate_PC,
                             "PC_population",
                             "blue",
                             multiplier_=multiplier,
                             StateM=StateM_PC,
                             selection=selection)
        plot_zoomed(spike_times_BC,
                    spiking_neurons_BC,
                    rate_BC,
                    "BC_population",
                    "green",
                    multiplier_=multiplier,
                    PC_pop=False,
                    StateM=StateM_BC)
        plot_detailed(StateM_PC, subset, multiplier_=multiplier)

        if not linear:
            slice_idx = []
            replay_ROI = np.where((150 <= bin_edges_PC)
                                  & (bin_edges_PC <= 850))
            replay = replay_circular(
                ISI_hist_PC[replay_ROI]) if analyse_replay else np.nan
        else:
            slice_idx = slice_high_activity(rate_PC, th=2, min_len=260)
            plot_raster(spike_times_PC,
                        spiking_neurons_PC,
                        rate_PC, [ISI_hist_PC, bin_edges_PC],
                        slice_idx,
                        "blue",
                        multiplier_=multiplier)
            if analyse_replay:
                replay, replay_results = replay_linear(spike_times_PC,
                                                       spiking_neurons_PC,
                                                       slice_idx,
                                                       pklf_name,
                                                       N=30)
            else:
                replay, replay_results = np.nan, {}
            if slice_idx and replay_results != {}:
                create_dir(dir_name)
                for bounds, tmp in replay_results.items():
                    fig_name = os.path.join(
                        dir_name, "%i-%i_replay.png" % (bounds[0], bounds[1]))
                    plot_posterior_trajectory(tmp["X_posterior"],
                                              tmp["fitted_path"], tmp["R"],
                                              fig_name)
            if save:
                save_replay_analysis(replay, replay_results, seed)

        mean_rate_PC, rate_ac_PC, max_ac_PC, t_max_ac_PC, f_PC, Pxx_PC = analyse_rate(
            rate_PC, 1000., slice_idx)
        mean_rate_BC, rate_ac_BC, max_ac_BC, t_max_ac_BC, f_BC, Pxx_BC = analyse_rate(
            rate_BC, 1000., slice_idx)
        plot_PSD(rate_PC,
                 rate_ac_PC,
                 f_PC,
                 Pxx_PC,
                 "PC_population",
                 "blue",
                 multiplier_=multiplier)
        plot_PSD(rate_BC,
                 rate_ac_BC,
                 f_BC,
                 Pxx_BC,
                 "BC_population",
                 "green",
                 multiplier_=multiplier)

        t_LFP, LFP, f_LFP, Pxx_LFP = analyse_estimated_LFP(
            StateM_PC, selection, slice_idx)
        plot_LFP(t_LFP, LFP, f_LFP, Pxx_LFP, multiplier_=multiplier)

        if save:
            save_LFP(t_LFP, LFP, seed)
            save_PSD(f_PC, Pxx_PC, f_BC, Pxx_BC, f_LFP, Pxx_LFP, seed)

        if TFR:
            coefs_PC, freqs_PC = calc_TFR(rate_PC, 1000., slice_idx)
            coefs_BC, freqs_BC = calc_TFR(rate_BC, 1000., slice_idx)
            coefs_LFP, freqs_LFP = calc_TFR(LFP[::10].copy(), 1000., slice_idx)
            if not linear or not slice_idx:
                plot_TFR(
                    coefs_PC, freqs_PC, "PC_population",
                    os.path.join(base_path, "figures",
                                 "%.2f_PC_population_wt.png" % multiplier))
                plot_TFR(
                    coefs_BC, freqs_BC, "BC_population",
                    os.path.join(base_path, "figures",
                                 "%.2f_BC_population_wt.png" % multiplier))
                plot_TFR(
                    coefs_LFP, freqs_LFP, "LFP",
                    os.path.join(base_path, "figures",
                                 "%.2f_LFP_wt.png" % multiplier))
            else:
                for i, bounds in enumerate(slice_idx):
                    fig_name = os.path.join(
                        dir_name,
                        "%i-%i_PC_population_wt.png" % (bounds[0], bounds[1]))
                    plot_TFR(coefs_PC[i], freqs_PC, "PC_population", fig_name)
                    fig_name = os.path.join(
                        dir_name,
                        "%i-%i_BC_population_wt.png" % (bounds[0], bounds[1]))
                    plot_TFR(coefs_BC[i], freqs_PC, "BC_population", fig_name)
                    fig_name = os.path.join(
                        dir_name, "%i-%i_LFP_wt.png" % (bounds[0], bounds[1]))
                    plot_TFR(coefs_LFP[i], freqs_LFP, "LFP", fig_name)

            if save:
                save_TFR(freqs_PC, coefs_PC, freqs_BC, coefs_BC, freqs_LFP,
                         coefs_LFP, seed)

        max_ac_ripple_PC, t_max_ac_ripple_PC = ripple_AC(rate_ac_PC, slice_idx)
        max_ac_ripple_BC, t_max_ac_ripple_BC = ripple_AC(rate_ac_BC, slice_idx)
        avg_ripple_freq_PC, ripple_power_PC = ripple(f_PC, Pxx_PC, slice_idx)
        avg_ripple_freq_BC, ripple_power_BC = ripple(f_BC, Pxx_BC, slice_idx)
        avg_ripple_freq_LFP, ripple_power_LFP = ripple(f_LFP, Pxx_LFP,
                                                       slice_idx)
        avg_gamma_freq_PC, gamma_power_PC = gamma(f_PC, Pxx_PC, slice_idx)
        avg_gamma_freq_BC, gamma_power_BC = gamma(f_BC, Pxx_BC, slice_idx)
        avg_gamma_freq_LFP, gamma_power_LFP = gamma(f_LFP, Pxx_LFP, slice_idx)

        if verbose:
            if not np.isnan(replay):
                print("Replay detected!")
            else:
                print("No replay detected...")
            print("Mean excitatory rate: %.3f" % mean_rate_PC)
            print("Mean inhibitory rate: %.3f" % mean_rate_BC)
            print("Average exc. ripple freq: %.3f" % avg_ripple_freq_PC)
            print("Exc. ripple power: %.3f" % ripple_power_PC)
            print("Average inh. ripple freq: %.3f" % avg_ripple_freq_BC)
            print("Inh. ripple power: %.3f" % ripple_power_BC)
            print("Average LFP ripple freq: %.3f" % avg_ripple_freq_LFP)
            print("LFP ripple power: %.3f" % ripple_power_LFP)

        return [
            multiplier, replay, mean_rate_PC, mean_rate_BC, avg_ripple_freq_PC,
            ripple_power_PC, avg_ripple_freq_BC, ripple_power_BC,
            avg_ripple_freq_LFP, ripple_power_LFP, avg_gamma_freq_PC,
            gamma_power_PC, avg_gamma_freq_BC, gamma_power_BC,
            avg_gamma_freq_LFP, gamma_power_LFP, max_ac_PC, max_ac_ripple_PC,
            max_ac_BC, max_ac_ripple_BC
        ]
    else:
        if verbose:
            print("No activity!")
        return [np.nan for _ in range(20)]
Ejemplo n.º 3
0
sme = SpikeMonitor(PE)
smi = SpikeMonitor(PI)
popre = PopulationRateMonitor(PE, bin=1*ms)
popri = PopulationRateMonitor(PI, bin=1*ms)
poprext = PopulationRateMonitor(MF, bin=1*ms)
bins = [0*ms, 50*ms, 100*ms, 150*ms, 200*ms, 250*ms, 300*ms, 350*ms, 400*ms, 450*ms, 500*ms,
        550*ms, 600*ms, 650*ms, 700*ms, 750*ms, 800*ms, 850*ms, 900*ms, 950*ms, 1000*ms]
isi = ISIHistogramMonitor(PE, bins)


run(10000*ms, report='text')

avgReplayInterval = replay(isi.count[3:17])  # bins from 150 to 850 (range of interest)

meanEr, rEAC, maxEAC, tMaxEAC, maxEACR, tMaxEACR, fE, PxxE, avgRippleFE, ripplePE = ripple(popre.rate, 1000)
avgGammaFE, gammaPE = gamma(fE, PxxE)
meanIr, rIAC, maxIAC, tMaxIAC, maxIACR, tMaxIACR, fI, PxxI, avgRippleFI, ripplePI = ripple(popri.rate, 1000)
avgGammaFI, gammaPI = gamma(fI, PxxI)

print 'Mean excitatory rate: ', meanEr
print 'Maximum exc. autocorrelation:', maxEAC, 'at', tMaxEAC, '[ms]'
print 'Maximum exc. AC in ripple range:', maxEACR, 'at', tMaxEACR, '[ms]'
print 'Mean inhibitory rate: ', meanIr
print 'Maximum inh. autocorrelation:', maxIAC, 'at', tMaxIAC, '[ms]'
print 'Maximum inh. AC in ripple range:', maxIACR, 'at', tMaxIACR, '[ms]'
print ''
print 'Average exc. ripple freq:', avgRippleFE
print 'Exc. ripple power:', ripplePE
print 'Average exc. gamma freq:', avgGammaFE
print 'Exc. gamma power:', gammaPE
print 'Average inh. ripple freq:', avgRippleFI
Ejemplo n.º 4
0
    def evaluate_with_lists(self, individual, verbose=False, plots=False):
        """Fitness error used by BluePyOpt for the optimization"""
        SM_PC, SM_BC, RM_PC, RM_BC = self.generate_model(individual,
                                                         verbose=verbose)

        try:
            wc_errors = [0., 0., 0., 0., 0., 0.]  # worst case scenario
            if SM_PC.num_spikes > 0 and SM_BC.num_spikes > 0:  # check if there is any activity
                # analyse spikes
                spike_times_PC, spiking_neurons_PC, rate_PC, ISI_hist_PC, bin_edges_PC = preprocess_monitors(
                    SM_PC, RM_PC)
                spike_times_BC, spiking_neurons_BC, rate_BC = preprocess_monitors(
                    SM_BC, RM_BC, calc_ISI=False)
                del SM_PC, SM_BC, RM_PC, RM_BC
                gc.collect()
                # analyse rates
                slice_idx = [] if not self.linear else slice_high_activity(
                    rate_PC, th=2, min_len=260)
                mean_rate_PC, rate_ac_PC, max_ac_PC, t_max_ac_PC, f_PC, Pxx_PC = analyse_rate(
                    rate_PC, 1000.0, slice_idx)
                mean_rate_BC, rate_ac_BC, max_ac_BC, t_max_ac_BC, f_BC, Pxx_BC = analyse_rate(
                    rate_BC, 1000.0, slice_idx)
                avg_ripple_freq_PC, ripple_power_PC = ripple(
                    f_PC, Pxx_PC, slice_idx)
                avg_ripple_freq_BC, ripple_power_BC = ripple(
                    f_BC, Pxx_BC, slice_idx)
                avg_gamma_freq_PC, gamma_power_PC = gamma(
                    f_PC, Pxx_PC, slice_idx)
                avg_gamma_freq_BC, gamma_power_BC = gamma(
                    f_BC, Pxx_BC, slice_idx)

                # these 2 flags are only used for the last rerun, but not during the optimization
                if verbose:
                    print("Mean excitatory rate: %.3f" % mean_rate_PC)
                    print("Mean inhibitory rate: %.3f" % mean_rate_BC)
                    print("Average exc. ripple freq: %.3f" %
                          avg_ripple_freq_PC)
                    print("Exc. ripple power: %.3f" % ripple_power_PC)
                    print("Average inh. ripple freq: %.3f" %
                          avg_ripple_freq_BC)
                    print("Inh. ripple power: %.3f" % ripple_power_BC)
                if plots:
                    from plots import plot_raster, plot_PSD, plot_zoomed
                    plot_raster(spike_times_PC,
                                spiking_neurons_PC,
                                rate_PC, [ISI_hist_PC, bin_edges_PC],
                                slice_idx,
                                "blue",
                                multiplier_=1)
                    plot_PSD(rate_PC,
                             rate_ac_PC,
                             f_PC,
                             Pxx_PC,
                             "PC_population",
                             "blue",
                             multiplier_=1)
                    plot_PSD(rate_BC,
                             rate_ac_BC,
                             f_BC,
                             Pxx_BC,
                             "BC_population",
                             "green",
                             multiplier_=1)
                    _ = plot_zoomed(spike_times_PC,
                                    spiking_neurons_PC,
                                    rate_PC,
                                    "PC_population",
                                    "blue",
                                    multiplier_=1)
                    plot_zoomed(spike_times_BC,
                                spiking_neurons_BC,
                                rate_BC,
                                "BC_population",
                                "green",
                                multiplier_=1,
                                PC_pop=False)

                # look for significant ripple peak close to 180 Hz
                ripple_peakE = np.exp(
                    -1 / 2 * (avg_ripple_freq_PC - 180.)**2 /
                    20**2) if not np.isnan(avg_ripple_freq_PC) else 0.
                ripple_peakI = 2 * np.exp(
                    -1 / 2 * (avg_ripple_freq_BC - 180.)**2 /
                    20**2) if not np.isnan(avg_ripple_freq_BC) else 0.
                # penalize gamma peak (in inhibitory pop) - binary variable, which might not be the best for this algo.
                no_gamma_peakI = 1. if np.isnan(avg_gamma_freq_BC) else 0.
                # look for high ripple/gamma power ratio
                ripple_ratioE = np.clip(ripple_power_PC / gamma_power_PC, 0.,
                                        5.)
                ripple_ratioI = np.clip(2 * ripple_power_BC / gamma_power_BC,
                                        0., 10.)
                # look for "low" exc. population rate (around 2.5 Hz)
                rateE = np.exp(-1 / 2 * (mean_rate_PC - 2.5)**2 / 1.0**2)
                # *-1 since the algorithm tries to minimize...
                errors = -1. * np.array([
                    ripple_peakE, ripple_peakI, no_gamma_peakI, ripple_ratioE,
                    ripple_ratioI, rateE
                ])
                return errors.tolist()
            else:
                return wc_errors
        except Exception:
            # Make sure exception and backtrace are thrown back to parent process
            raise Exception("".join(
                traceback.format_exception(*sys.exc_info())))
fig3.savefig(figName)

'''
# average speed
mu = 2*np.pi / 0.484  # this shouldn't be hard coded !!!
sigma = 1
'''

# -------------------------------------------------
# Analysis of firing rates (from spw_network....py)
# -------------------------------------------------

excRate = popre.values()

meanEr, rEAC, maxEAC, tMaxEAC, maxEACR, tMaxEACR, fE, PxxE, avgRippleFE, ripplePE = ripple(excRate, 1000)
avgGammaFE, gammaPE = gamma(fE, PxxE)


fig4 = plt.figure(figsize=(10, 8))

ax = fig4.add_subplot(3, 1, 1)
ax.plot(np.linspace(0, 9999, 10000), excRate, 'b-')
ax.set_title('Exc. population rate')
ax.set_xlabel('Time [ms]')

rEACPlot = rEAC[2:201]  # 500 - 5 Hz interval

ax2 = fig4.add_subplot(3, 1, 2)
ax2.plot(np.linspace(2, 200, len(rEACPlot)), rEACPlot, 'b-', lw=1.5)
ax2.set_title('Autocorrelogram (2-200 ms)')
ax2.set_xlabel('Time [ms]')