Beispiel #1
0
 def test_user_tags(self):
     pre = '0;0'
     post = 'mon;mon**2-1'
     raw = Raw(pre_expr=pre, post_expr=post)
     tags = raw._transform_user_tags()
     self.assertIn('user_tag_1', tags)
     self.assertIn('user_tag_2', tags)
     self.assertEqual(tags['user_tag_1'], pre)
     self.assertEqual(tags['user_tag_2'], post)
Beispiel #2
0
    def build_simulator(self, n=4):

        self.conn = numpy.zeros((n, n))  # , numpy.int32)
        for i in range(self.conn.shape[0] - 1):
            self.conn[i, i + 1] = 1

        self.dist = numpy.r_[:n * n].reshape((n, n))
        self.dist = numpy.array(self.dist, dtype=float)

        self.sim = Simulator(
            conduction_speed=1.0,
            coupling=IdCoupling(),
            surface=None,
            stimulus=None,
            integrator=Identity(dt=1.0),
            initial_conditions=numpy.ones((n * n, 1, n, 1)),
            simulation_length=10.0,
            connectivity=Connectivity(region_labels=numpy.array(['']),
                                      weights=self.conn,
                                      tract_lengths=self.dist,
                                      speed=numpy.array([1.0]),
                                      centres=numpy.array([0.0])),
            model=Sum(),
            monitors=(Raw(), ),
        )
        self.sim.configure()
Beispiel #3
0
 def _create_sim(self, integrator=None, inhom_mmpr=False, delays=False,
         run_sim=True):
     mpr = MontbrioPazoRoxin()
     conn = Connectivity.from_file()
     if inhom_mmpr:
         dispersion = 1 + np.random.randn(conn.weights.shape[0])*0.1
         mpr = MontbrioPazoRoxin(eta=mpr.eta*dispersion)
     conn.speed = np.r_[3.0 if delays else np.inf]
     if integrator is None:
         dt = 0.01
         integrator = EulerDeterministic(dt=dt)
     else:
         dt = integrator.dt
     sim = Simulator(connectivity=conn, model=mpr, integrator=integrator, 
         monitors=[Raw()],
         simulation_length=0.1)  # 10 steps
     sim.configure()
     if not delays:
         self.assertTrue((conn.idelays == 0).all())
     buf = sim.history.buffer[...,0]
     # kernel has history in reverse order except 1st element 🤕
     rbuf = np.concatenate((buf[0:1], buf[1:][::-1]), axis=0)
     state = np.transpose(rbuf, (1, 0, 2)).astype('f')
     self.assertEqual(state.shape[0], 2)
     self.assertEqual(state.shape[2], conn.weights.shape[0])
     if isinstance(sim.integrator, IntegratorStochastic):
         sim.integrator.noise.reset_random_stream()
     if run_sim:
         (t,y), = sim.run()
         return sim, state, t, y
     else:
         return sim
 def test_expr_pre(self):
     sim, ys = self._run_sim(5, models.Generic2dOscillator(),
                             Raw(pre_expr='V;W;V**2;W-V', post_expr=''))
     self.assertTrue(hasattr(sim.monitors[0], '_transforms'))
     v, w, v2, wmv = ys.transpose((1, 0, 2, 3))
     self.assertTrue(numpy.allclose(v**2, v2))
     self.assertTrue(numpy.allclose(w - v, wmv))
Beispiel #5
0
 def test_expr_post(self):
     sim, ys = self._run_sim(
         5, models.Generic2dOscillator(),
         Raw(pre_expr='V;W;V;W', post_expr=';;mon**2; exp(mon)'))
     self.assertTrue(hasattr(sim.monitors[0], '_transforms'))
     v, w, v2, ew = ys.transpose((1, 0, 2, 3))
     self.assertTrue(numpy.allclose(v**2, v2))
     self.assertTrue(numpy.allclose(numpy.exp(w), ew))
def test(dt=0.1, noise_strength=0.001, config=CONFIGURED):

    # Select the regions for the fine scale modeling with NEST spiking networks
    nest_nodes_ids = []  # the indices of fine scale regions modeled with NEST
    # In this example, we model parahippocampal cortices (left and right) with NEST
    connectivity = Connectivity.from_file(CONFIGURED.DEFAULT_CONNECTIVITY_ZIP)
    for id in range(connectivity.region_labels.shape[0]):
        if connectivity.region_labels[id].find("hippo") > 0:
            nest_nodes_ids.append(id)
    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.integrator.dt = dt
    simulator.integrator.noise.nsig = np.array([noise_strength])
    simulator.model = ReducedWongWangExcIOInhI()

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

    # Build a NEST network model with the corresponding builder
    # Using all default parameters for this example
    nest_model_builder = RedWWExcIOInhIMultisynapseBuilder(simulator,
                                                           nest_nodes_ids,
                                                           config=config)
    nest_model_builder.configure()
    for prop in [
            "min_delay", "tvb_dt", "tvb_model", "tvb_connectivity",
            "tvb_weights", "tvb_delays", "number_of_nodes",
            "number_of_spiking_nodes", "spiking_nodes_labels",
            "number_of_populations", "populations_models", "populations_nodes",
            "populations_scales", "populations_sizes", "populations_params",
            "populations_connections_labels", "populations_connections_models",
            "populations_connections_nodes", "populations_connections_weights",
            "populations_connections_delays",
            "populations_connections_receptor_types",
            "populations_connections_conn_spec", "nodes_connections_labels",
            "nodes_connections_models", "nodes_connections_source_nodes",
            "nodes_connections_target_nodes", "nodes_connections_weights",
            "nodes_connections_delays", "nodes_connections_receptor_types",
            "nodes_connections_conn_spec"
    ]:
        print("%s:\n%s\n\n" % (prop, str(getattr(nest_model_builder, prop))))
Beispiel #7
0
 def _prep_sim(self, coupling) -> Simulator:
     "Prepare simulator for testing a coupling function."
     con = Connectivity.from_file()
     con.weights[:] = 1.0
     # con = Connectivity(
     #     region_labels=np.array(['']),
     #     weights=con.weights[:5][:,:5],
     #     tract_lengths=con.tract_lengths[:5][:,:5],
     #     speed=np.array([10.0]),
     #     centres=np.array([0.0]))
     sim = Simulator(connectivity=con,
                     model=LinearModel(gamma=np.r_[0.0]),
                     coupling=coupling,
                     integrator=Identity(dt=1.0),
                     monitors=[Raw()],
                     simulation_length=0.5)
     sim.configure()
     return sim
Beispiel #8
0
def test(dt=0.1, noise_strength=0.001, config=CONFIGURED):
    # Select the regions for the fine scale modeling with ANNarchy spiking networks
    anarchy_nodes_ids = list(
        range(10))  # the indices of fine scale regions modeled with ANNarchy
    # In this example, we model parahippocampal cortices (left and right) with ANNarchy
    connectivity = Connectivity.from_file(CONFIGURED.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.integrator.dt = dt
    # simulator.integrator.noise.nsig = np.array([noise_strength])
    simulator.model = ReducedWongWangExcIOInhI()

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

    # Build a ANNarchy network model with the corresponding builder
    # Using all default parameters for this example
    anarchy_model_builder = BasalGangliaIzhikevichBuilder(simulator,
                                                          anarchy_nodes_ids,
                                                          config=config)
    anarchy_model_builder.configure()
    for prop in [
            "min_delay", "tvb_dt", "tvb_model", "tvb_connectivity",
            "tvb_weights", "tvb_delays", "number_of_nodes",
            "number_of_spiking_nodes", "spiking_nodes_labels",
            "number_of_populations", "populations_models", "populations_nodes",
            "populations_scales", "populations_sizes", "populations_params",
            "populations_connections_labels", "populations_connections_models",
            "populations_connections_nodes", "populations_connections_weights",
            "populations_connections_delays",
            "populations_connections_receptor_types",
            "populations_connections_conn_spec", "nodes_connections_labels",
            "nodes_connections_models", "nodes_connections_source_nodes",
            "nodes_connections_target_nodes", "nodes_connections_weights",
            "nodes_connections_delays", "nodes_connections_receptor_types",
            "nodes_connections_conn_spec"
    ]:
        print("%s:\n%s\n\n" %
              (prop, str(getattr(anarchy_model_builder, prop))))
Beispiel #9
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
Beispiel #10
0
def create_time_series_region_object():
    config = CONFIGURED

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

    simulator = Simulator()
    simulator.model = ReducedWongWangExcIOInhI()

    def boundary_fun(state):
        state[state < 0] = 0.0
        state[state > 1] = 1.0
        return state

    simulator.boundary_fun = boundary_fun
    simulator.connectivity = connectivity
    simulator.integrator.dt = \
        float(int(numpy.round(simulator.integrator.dt /
                              config.nest.NEST_MIN_DT))) * config.nest.NEST_MIN_DT

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

    number_of_regions = simulator.connectivity.region_labels.shape[0]
    nest_nodes_ids = []

    for id in range(number_of_regions):
        if simulator.connectivity.region_labels[id].find("hippo") > 0:
            nest_nodes_ids.append(id)

    nest_model_builder = \
        RedWWExcIOInhIBuilder(simulator, nest_nodes_ids, config=config)

    nest_network = nest_model_builder.build_nest_network()

    tvb_nest_builder = \
        RedWWexcIOinhIBuilder(simulator, nest_network, nest_nodes_ids, config=config)

    tvb_nest_builder.tvb_to_nest_interfaces = \
        [{"model": "current", "parameter": "I_e", "sign": 1,
          "connections": {"S_e": ["E", "I"]}}]

    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()

    simulator.configure(tvb_nest_interface=tvb_nest_model)
    results = simulator.run(simulation_length=100.0)
    time = results[0][0]
    source = results[0][1]

    source_ts = TimeSeriesRegion(
        data=source,
        time=time,
        connectivity=simulator.connectivity,
        labels_ordering=[
            "Time", "Synaptic Gating Variable", "Region", "Neurons"
        ],
        labels_dimensions={
            "Synaptic Gating Variable": ["S_e", "S_i"],
            "Region": simulator.connectivity.region_labels.tolist()
        },
        sample_period=simulator.integrator.dt)

    return source_ts
Beispiel #11
0
 def _sample_with_tvb_monitor(self, step, state):
     return Raw.sample(self, step, state)
Beispiel #12
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]
Beispiel #13
0
    simulator = Simulator()
    simulator.model = ReducedWongWangExcIOInhI()

    def boundary_fun(state):
        state[state < 0] = 0.0
        state[state > 1] = 1.0
        return state

    # Synaptic gating state variables S_e, S_i need to be in the interval [0, 1]
    simulator.boundary_fun = boundary_fun
    simulator.connectivity = connectivity
    # TODO: Try to make this part of the __init__ of the Simulator!
    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)
    # mon_bold = Bold(period=2000.)
    # mon_eeg = EEG(period=simulator.integrator.dt)
    simulator.monitors = (mon_raw, )  # mon_bold, mon_eeg

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

    # 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 id in range(number_of_regions):
        if simulator.connectivity.region_labels[id].find("hippo") > 0:
            nest_nodes_ids.append(id)

    # Build a NEST network model with the corresponding builder
Beispiel #14
0
 def test_expr_tim(self):
     sim, ys = self._run_sim(5, models.Epileptor(),
                             Raw(pre_expr='-y0+y3;y2', post_expr='mon;mon'))
     self.assertTrue(hasattr(sim.monitors[0], '_transforms'))
     lfp, slow = ys.transpose((1, 0, 2, 3))
Beispiel #15
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