コード例 #1
0
def main_example(tvb_sim_model,
                 connectivity_zip=CONFIGURED.DEFAULT_CONNECTIVITY_ZIP,
                 dt=0.1,
                 noise_strength=0.001,
                 simulation_length=100.0,
                 config=CONFIGURED):

    plotter = Plotter(config)

    # --------------------------------------1. Load TVB connectivity----------------------------------------------------
    connectivity = Connectivity.from_file(connectivity_zip)
    connectivity.configure()
    plotter.plot_tvb_connectivity(connectivity)

    # ----------------------2. Define a TVB simulator (model, integrator, monitors...)----------------------------------

    # Create a TVB simulator and set all desired inputs
    # (connectivity, model, surface, stimuli etc)
    # We choose all defaults in this example
    simulator = Simulator()
    simulator.integrator = HeunStochastic(dt=dt)
    simulator.integrator.noise.nsig = np.array(ensure_list(noise_strength))
    simulator.model = tvb_sim_model
    simulator.connectivity = connectivity
    mon_raw = Raw(period=simulator.integrator.dt)
    simulator.monitors = (mon_raw, )

    # -----------------------------------3. Simulate and gather results-------------------------------------------------

    # Configure the simulator with the TVB-NEST interface...
    # simulator.configure(tvb_nest_interface=tvb_nest_model)
    simulator.configure()
    # ...and simulate!
    t_start = time.time()
    results = simulator.run(simulation_length=simulation_length)
    print("\nSimulated in %f secs!" % (time.time() - t_start))

    # -------------------------------------------6. Plot results--------------------------------------------------------

    plot_results(results, simulator, None, "State Variables",
                 simulator.model.variables_of_interest, plotter)

    return connectivity, results
コード例 #2
0
def prepare_launch_default_simulation():
    config = Config(output_base="outputs/")
    config.figures.SAVE_FLAG = False
    config.figures.SHOW_FLAG = False
    config.figures.MATPLOTLIB_BACKEND = "Agg"
    plotter = Plotter(config)

    connectivity = Connectivity.from_file(
        os.path.join(Config.DEFAULT_SUBJECT_PATH,
                     Config.DEFAULT_CONNECTIVITY_ZIP))
    connectivity.configure()

    # Create a TVB simulator and set all desired inputs
    # (connectivity, model, surface, stimuli etc)
    # We choose all defaults in this example
    simulator = Simulator()
    simulator.model = ReducedWongWangExcIOInhI()
    simulator.connectivity = connectivity
    simulator.integrator.dt = float(
        int(np.round(simulator.integrator.dt /
                     config.nest.NEST_MIN_DT))) * config.nest.NEST_MIN_DT
    # Some extra monitors for neuroimaging measures:
    mon_raw = Raw(period=simulator.integrator.dt)
    simulator.monitors = (mon_raw, )  # mon_bold, mon_eeg

    # Select the regions for the fine scale modeling with NEST spiking networks
    number_of_regions = simulator.connectivity.region_labels.shape[0]
    nest_nodes_ids = []  # the indices of fine scale regions modeled with NEST
    # In this example, we model parahippocampal cortices (left and right) with NEST
    for rid in range(number_of_regions):
        if simulator.connectivity.region_labels[rid].find("hippo") > 0:
            nest_nodes_ids.append(rid)

    # Build a NEST network model with the corresponding builder
    # Using all default parameters for this example
    nest_model_builder = RedWWExcIOInhIBuilder(simulator, nest_nodes_ids)
    nest_model_builder.populations_names = ["E", "I"]
    nest_model_builder.populations_scales = [1.0, 0.7]
    nest_model_builder.default_synapse["params"]["rule"] = "fixed_indegree"

    # Connection weights
    # Choosing the values resulting from J_N = 150 pA and J_i = 1000 pA
    w_ee = 150.0
    w_ei = -1000.0
    w_ie = 150.0
    w_ii = -1000.0

    # Within node connections' weights
    # TODO: take care of J_N units conversion from TVB to NEST!
    nest_model_builder.population_connectivity_synapses_weights = np.array([
        [w_ee, w_ei],  # exc_i -> exc_i, inh_i -> exc_i
        [w_ie, w_ii]
    ])  # exc_i -> inh_i, inh_i -> inh_i
    nest_model_builder.population_connectivity_synapses_delays = np.array(
        nest_model_builder.tvb_dt / 4)

    # Between node connections
    # Given that w_ee == w_ie = J_N, we need only one connection type
    nest_model_builder.node_connections = [{
        "src_population":
        "E",
        "trg_population": ["E", "I"],
        "model":
        nest_model_builder.default_synapse["model"],
        "params":
        nest_model_builder.default_synapse["params"],
        "weight":
        w_ee,  # weight scaling the TVB connectivity weight
        "delay":
        0.0
    }]  # additional delay to the one of TVB connectivity

    connections = OrderedDict()
    connections["E"] = "E"
    connections["I"] = "I"
    nest_model_builder.output_devices = [{
        "model":
        "spike_detector",
        "props":
        config.nest.NEST_OUTPUT_DEVICES_PARAMS_DEF["spike_detector"],
        "nodes":
        None,
        "connections":
        connections
    }]

    nest_network = nest_model_builder.build_nest_network()

    # Build a TVB-NEST interface with all the appropriate connections between the
    # TVB and NEST modelled regions
    # Using all default parameters for this example
    tvb_nest_builder = RedWWexcIOinhIBuilder(simulator, nest_network,
                                             nest_nodes_ids)

    # NEST -> TVB:
    # For current transmission from TVB to NEST,
    # either choose a NEST dc_generator device:
    # tvb_nest_builder.tvb_to_nest_interfaces = [{"model": "dc_generator", "sign": 1,
    #      "connections": {"S_e": ["E", "I"]}}]
    # or modify directly the external current stimulus parameter:
    tvb_nest_builder.tvb_to_nest_interfaces = [{
        "model": "current",
        "parameter": "I_e",
        "sign": 1,
        "connections": {
            "S_e": ["E", "I"]
        }
    }]

    # NEST -> TVB:
    # Use S_e and S_i instead of r_e and r_i
    # for transmitting to the TVB state variables directly
    connections = OrderedDict()
    connections["r_e"] = "E"
    connections["r_i"] = "I"
    tvb_nest_builder.nest_to_tvb_interfaces = [{
        "model": "spike_detector",
        "params": {},
        "connections": connections
    }]

    tvb_nest_model = tvb_nest_builder.build_interface()

    # Configure the simulator with the TVB-NEST interface...
    simulator.configure(tvb_nest_interface=tvb_nest_model)
    # ...and simulate!
    t = time.time()
    results = simulator.run(simulation_length=100.0)

    return connectivity.weights, connectivity.tract_lengths, results[0][1]
コード例 #3
0
TvbProfile.set_profile(TvbProfile.LIBRARY_PROFILE)

from tvb_nest.config import CONFIGURED
from tvb_nest.simulator_tvb.simulator import Simulator
from tvb_nest.interfaces.builders.red_ww_exc_io_inh_i import RedWWexcIOinhIBuilder
from tvb_nest.simulator_nest.models_builders.red_ww_exc_io_inh_i import RedWWExcIOInhIBuilder
from tvb_nest.simulator_tvb.model_reduced_wong_wang_exc_io_inh_i import ReducedWongWangExcIOInhI
from tvb_nest.plot.plotter import Plotter
from tvb_scripts.time_series.model import TimeSeriesRegion
from tvb.datatypes.connectivity import Connectivity
from tvb.simulator.monitors import Raw  # , Bold  # , EEG

if __name__ == "__main__":

    config = CONFIGURED
    plotter = Plotter(config)

    connectivity = Connectivity.from_file(config.DEFAULT_CONNECTIVITY_ZIP)
    connectivity.configure()
    plotter.plot_tvb_connectivity(connectivity)

    # ----------------------2. Define a TVB simulator (model, integrator, monitors...)-----------------------------------

    # Create a TVB simulator and set all desired inputs
    # (connectivity, model, surface, stimuli etc)
    # We choose all defaults in this example
    simulator = Simulator()
    simulator.model = ReducedWongWangExcIOInhI()

    def boundary_fun(state):
        state[state < 0] = 0.0
コード例 #4
0
from collections import OrderedDict
from tvb.datatypes.connectivity import Connectivity
from tvb.simulator.monitors import Raw
from tvb_timeseries.model.timeseries import Timeseries
from tvb_nest.base.config import *
from tvb_nest.plot.plotter import Plotter
from tvb_nest.base.simulator import Simulator
from tvb_nest.tvb_models.reduced_wong_wang_exc_io_inh_i import ReducedWongWangExcIOInhI
from tvb_nest.nest_models_builders.red_ww_exc_io_inh_i import RedWWExcIOInhIBuilder
from tvb_nest.interface_builders.red_ww_exc_io_inh_i import RedWWexcIOinhIBuilder

config = Config(output_base="outputs/")
config.figures.SAVE_FLAG = False
config.figures.SHOW_FLAG = False
config.figures.MATPLOTLIB_BACKEND = "Agg"
plotter = Plotter(config)

connectivity = Connectivity.from_file(
    os.path.join(DEFAULT_SUBJECT_PATH, DEFAULT_CONNECTIVITY_ZIP))
connectivity.configure()
#plotter.plot_tvb_connectivity(connectivity)

# Create a TVB simulator and set all desired inputs
# (connectivity, model, surface, stimuli etc)
# We choose all defaults in this example
simulator = Simulator()
simulator.model = ReducedWongWangExcIOInhI()
simulator.connectivity = connectivity
simulator.integrator.dt = float(
    int(np.round(simulator.integrator.dt /
                 config.nest.NEST_MIN_DT))) * config.nest.NEST_MIN_DT
コード例 #5
0
def plot_results(results,
                 simulator,
                 tvb_nest_model,
                 tvb_state_variable_type_label="",
                 tvb_state_variables_labels=[],
                 plotter=Plotter(CONFIGURED)):
    t = results[0][0]
    source = results[0][1]

    # -------------------------------------------6. Plot results--------------------------------------------------------

    #   Remove ts_type="Region" this argument too for TVB TimeSeriesRegion
    source_ts = TimeSeriesRegion(  # substitute with TimeSeriesRegion fot TVB like functionality
        data=source, time=t,
        connectivity=simulator.connectivity,
        # region_mapping=head.cortical_region_mapping,
        # region_mapping_volume=head.region_volume_mapping,
        labels_ordering=["Time", tvb_state_variable_type_label, "Region", "Neurons"],
        labels_dimensions={tvb_state_variable_type_label: tvb_state_variables_labels,
                           "Region": simulator.connectivity.region_labels.tolist()},
        sample_period=simulator.integrator.dt)

    # Plot time_series
    plotter.plot_timeseries(source_ts, title="Region Time Series")
    plotter.plot_raster(source_ts, title="Region Time Series Raster")
    # # ...interactively as well
    # plotter.plot_timeseries_interactive(source_ts)

    if tvb_nest_model is None:
        return

    # Focus on the nodes modelled in NEST:
    try:
        source_ts_nest = source_ts.get_subspace(tvb_nest_model.nest_nodes_ids)
        plotter.plot_timeseries(source_ts_nest,
                                title="NEST nodes Region Time Series")
        plotter.plot_raster(source_ts_nest,
                            title="NEST nodes Region Time Series Raster")
    except:
        pass

    # In all the following we assume that all populations are in the same (equal number of) regions,
    # whereas we average across individual neurons

    # Plot NEST multimeter variables
    multimeter_mean_data = tvb_nest_model.get_mean_data_from_NEST_multimeter_to_TVBTimeSeries(
    )
    if multimeter_mean_data is not None and multimeter_mean_data.size > 0:
        plotter.plot_multimeter_timeseries(
            multimeter_mean_data,
            plot_per_variable=True,
            time_series_class=TimeSeriesRegion,
            time_series_args={},
            var_pop_join_str=" - ",
            default_population_label="population",
            title="NEST region time series")
        plotter.plot_multimeter_raster(multimeter_mean_data,
                                       plot_per_variable=True,
                                       time_series_class=TimeSeriesRegion,
                                       time_series_args={},
                                       var_pop_join_str=" - ",
                                       default_population_label="population",
                                       title="NEST region time series raster")

    # Plot spikes and mean field spike rates
    rates, spike_detectors = \
        tvb_nest_model.get_mean_spikes_rates_from_NEST_to_TVBTimeSeries(
            spikes_kernel_width=1.0,  # ms
            spikes_kernel_overlap=0.5, time=t)
    if spike_detectors is not None and rates.size > 0:
        plotter.plot_spikes(spike_detectors,
                            rates=rates,
                            title='Population spikes and mean spike rate')

    # ------------------------------------Testing code for xarray TimeSeries--------------------------------------------

    nest_network = tvb_nest_model.nest_network
    multimeter_mean_data = nest_network.get_mean_data_from_multimeter()

    if multimeter_mean_data.size > 0:
        from tvb_scripts.time_series.time_series_xarray import TimeSeries as TimeSeriesXarray

        ts = TimeSeriesXarray(multimeter_mean_data)
        # ts.plot(plotter=plotter, )
        ts.plot_timeseries(plotter=plotter)
        ts.plot_raster(plotter=plotter,
                       linestyle="--",
                       alpha=0.5,
                       linewidth=0.5)
        # print(ts[0].shape)
        # print(ts[:, 0].shape)
        # print(ts[:, "V_m"].shape)
        # print(ts[:, :, 0].shape)
        # print(ts[:, ["V_m"], 1, :].shape)
        # ts[::, ["V_m"], 1, :] = TimeSeriesXarray(ts[:, ["V_m"], 1, :])
        # ts[::, ["V_m"], 1, :] = TimeSeriesXarray(ts[:, ["V_m"], 1, :].data, time=ts[:, ["V_m"], 1, :].time)

    # ------------------------------------Testing code for plotting xarray data-----------------------------------------

    rates = \
        nest_network.compute_spikes_rates(mode="per_neuron", population_devices=None, regions=None,
                                          devices_dim_name="Population", name="Spikes rates from NEST network",
                                          spikes_kernel_width=1.0,  # spikes_kernel_n_intervals=10,
                                          spikes_kernel_overlap=0.5, min_spike_interval=None, time=t,
                                          spikes_kernel=None)[0]
    if rates.size > 0:
        rates.plot(x=rates.dims[0],
                   y=rates.dims[3],
                   row=rates.dims[2],
                   col=rates.dims[1],
                   robust=True)
        plotter.base._save_figure(figure_name="Spike rates per neuron")
コード例 #6
0
def main_example(tvb_sim_model,
                 nest_model_builder,
                 tvb_nest_builder,
                 nest_nodes_ids,
                 nest_populations_order=100,
                 connectivity=None,
                 connectivity_zip=CONFIGURED.DEFAULT_CONNECTIVITY_ZIP,
                 simulation_length=100.0,
                 tvb_state_variable_type_label="Synaptic Gating Variable",
                 delays=True,
                 dt=0.1,
                 noise_strength=0.001,
                 exclusive_nodes=False,
                 config=CONFIGURED):

    plotter = Plotter(config)

    # --------------------------------------1. Load TVB connectivity----------------------------------------------------
    if connectivity is None:
        connectivity = Connectivity.from_file(connectivity_zip)
    connectivity.configure()
    plotter.plot_tvb_connectivity(connectivity)
    if not delays:
        connectivity.tract_lengths /= 100000.0
        connectivity.configure()
    plotter.base.plot_regions2regions(connectivity.delays,
                                      connectivity.region_labels, 111,
                                      "Delays")
    plotter.base._save_figure(figure_name="Delays")

    # ----------------------2. Define a TVB simulator (model, integrator, monitors...)----------------------------------

    # Create a TVB simulator and set all desired inputs
    # (connectivity, model, surface, stimuli etc)
    # We choose all defaults in this example
    simulator = Simulator()
    simulator.integrator.dt = dt
    simulator.integrator.noise.nsig = np.array([noise_strength])
    simulator.model = tvb_sim_model

    simulator.connectivity = connectivity
    mon_raw = Raw(period=simulator.integrator.dt)
    simulator.monitors = (mon_raw, )

    # ------3. Build the NEST network model (fine-scale regions' nodes, stimulation devices, spike_detectors etc)-------

    print("Building NEST network...")
    tic = time.time()

    # Build a NEST network model with the corresponding builder
    # Using all default parameters for this example
    nest_model_builder = nest_model_builder(simulator,
                                            nest_nodes_ids,
                                            config=config)
    # Common order of neurons' number per population:
    nest_model_builder.populations_order = nest_populations_order
    nest_network = nest_model_builder.build_nest_network()

    print("Done! in %f min" % ((time.time() - tic) / 60))

    # -----------------------------------4. Build the TVB-NEST interface model -----------------------------------------

    print("Building TVB-NEST interface...")
    tic = time.time()
    # Build a TVB-NEST interface with all the appropriate connections between the
    # TVB and NEST modelled regions
    # Using all default parameters for this example
    tvb_nest_builder = tvb_nest_builder(simulator, nest_network,
                                        nest_nodes_ids, exclusive_nodes)
    tvb_nest_model = tvb_nest_builder.build_interface()
    print("Done! in %f min" % ((time.time() - tic) / 60))

    # -----------------------------------5. Simulate and gather results-------------------------------------------------

    # Configure the simulator with the TVB-NEST interface...
    simulator.configure(tvb_nest_interface=tvb_nest_model)
    # ...and simulate!
    t_start = time.time()
    results = simulator.run(simulation_length=simulation_length)
    # Integrate NEST one more NEST time step so that multimeters get the last time point
    # unless you plan to continue simulation later
    simulator.run_spiking_simulator(
        simulator.tvb_nest_interface.nest_instance.GetKernelStatus(
            "resolution"))
    # Clean-up NEST simulation
    if simulator.run_spiking_simulator == simulator.tvb_nest_interface.nest_instance.Run:
        simulator.tvb_nest_interface.nest_instance.Cleanup()
    print("\nSimulated in %f secs!" % (time.time() - t_start))

    # -------------------------------------------6. Plot results--------------------------------------------------------

    plot_results(results, simulator, tvb_nest_model,
                 tvb_state_variable_type_label,
                 simulator.model.variables_of_interest, plotter)

    return connectivity, results