Esempio n. 1
0
 def from_file(filepath, **kwargs):
     result = TVBConnectivity.from_file(filepath)
     if isinstance(result, TVBConnectivity):
         return Connectivity.from_tvb_instance(result, **kwargs)
     else:
         return Connectivity.from_instance(result, **kwargs)
Esempio n. 2
0
    def configure(self,
                  dt=2**-3,
                  model=ModelsEnum.GENERIC_2D_OSCILLATOR.get_class(),
                  speed=4.0,
                  coupling_strength=0.00042,
                  method=HeunDeterministic,
                  surface_sim=False,
                  default_connectivity=True,
                  with_stimulus=False):
        """
        Create an instance of the Simulator class, by default use the
        generic plane oscillator local dynamic model and the deterministic 
        version of Heun's method for the numerical integration.
        
        """
        self.method = method

        if default_connectivity:
            white_matter = Connectivity.from_file()
            region_mapping = RegionMapping.from_file(
                source_file="regionMapping_16k_76.txt")
        else:
            white_matter = Connectivity.from_file(
                source_file="connectivity_192.zip")
            region_mapping = RegionMapping.from_file(
                source_file="regionMapping_16k_192.txt")
        region_mapping.surface = CorticalSurface.from_file()

        white_matter_coupling = coupling.Linear(
            a=numpy.array([coupling_strength]))
        white_matter.speed = numpy.array(
            [speed])  # no longer allow scalars to numpy array promotion

        dynamics = model()

        if issubclass(method, IntegratorStochastic):
            hisss = noise.Additive(nsig=numpy.array([2**-11]))
            integrator = method(dt=dt, noise=hisss)
        else:
            integrator = method(dt=dt)

        if surface_sim:
            local_coupling_strength = numpy.array([2**-10])
            default_cortex = Cortex.from_file()
            default_cortex.region_mapping_data = region_mapping
            default_cortex.coupling_strength = local_coupling_strength
            if default_connectivity:
                default_cortex.local_connectivity = LocalConnectivity.from_file(
                )
            else:
                default_cortex.local_connectivity = LocalConnectivity()
            default_cortex.local_connectivity.surface = default_cortex.region_mapping_data.surface
            # TODO stimulus
        else:
            default_cortex = None
            if with_stimulus:
                weights = StimuliRegion.get_default_weights(
                    white_matter.weights.shape[0])
                weights[self.stim_nodes] = 1.
                stimulus = StimuliRegion(temporal=Linear(parameters={
                    "a": 0.0,
                    "b": self.stim_value
                }),
                                         connectivity=white_matter,
                                         weight=weights)

        # Order of monitors determines order of returned values.
        self.sim = simulator.Simulator()
        self.sim.surface = default_cortex
        self.sim.model = dynamics
        self.sim.integrator = integrator
        self.sim.connectivity = white_matter
        self.sim.coupling = white_matter_coupling
        self.sim.monitors = self.monitors
        if with_stimulus:
            self.sim.stimulus = stimulus
        self.sim.configure()
Esempio n. 3
0
    def configure(self,
                  dt=2**-3,
                  model=models.Generic2dOscillator,
                  speed=4.0,
                  coupling_strength=0.00042,
                  method=HeunDeterministic,
                  surface_sim=False,
                  default_connectivity=True):
        """
        Create an instance of the Simulator class, by default use the
        generic plane oscillator local dynamic model and the deterministic 
        version of Heun's method for the numerical integration.
        
        """
        self.method = method

        if default_connectivity:
            white_matter = Connectivity.from_file()
            region_mapping = RegionMapping.from_file(
                source_file="regionMapping_16k_76.txt")
        else:
            white_matter = Connectivity.from_file(
                source_file="connectivity_192.zip")
            region_mapping = RegionMapping.from_file(
                source_file="regionMapping_16k_192.txt")
        region_mapping.surface = CorticalSurface.from_file()

        white_matter_coupling = coupling.Linear(
            a=numpy.array([coupling_strength]))
        white_matter.speed = numpy.array(
            [speed])  # no longer allow scalars to numpy array promotion

        dynamics = model()

        if issubclass(method, IntegratorStochastic):
            hisss = noise.Additive(nsig=numpy.array([2**-11]))
            integrator = method(dt=dt, noise=hisss)
        else:
            integrator = method(dt=dt)

        if surface_sim:
            local_coupling_strength = numpy.array([2**-10])
            default_cortex = Cortex.from_file()
            default_cortex.region_mapping_data = region_mapping
            default_cortex.coupling_strength = local_coupling_strength
            if default_connectivity:
                default_cortex.local_connectivity = LocalConnectivity.from_file(
                )
            else:
                default_cortex.local_connectivity = LocalConnectivity()
            default_cortex.local_connectivity.surface = default_cortex.region_mapping_data.surface
        else:
            default_cortex = None

        # Order of monitors determines order of returned values.
        self.sim = simulator.Simulator()
        self.sim.surface = default_cortex
        self.sim.model = dynamics
        self.sim.integrator = integrator
        self.sim.connectivity = white_matter
        self.sim.coupling = white_matter_coupling
        self.sim.monitors = self.monitors
        self.sim.configure()
import matplotlib as mpl
mpl.use('Agg')

from tvb.datatypes.connectivity import Connectivity

from tvb_nest.config import Config

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

from tvb_nest.examples.example import main_example
from tvb_nest.nest_models.builders.models.red_ww_exc_io_inh_i import RedWWExcIOInhIBuilder
from tvb_nest.interfaces.builders.models.red_ww_exc_io_inh_i \
    import RedWWexcIOinhIBuilder as InterfaceRedWWexcIOinhIBuilder
from tvb.simulator.models.reduced_wong_wang_exc_io_inh_i import ReducedWongWangExcIOInhI


# 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(config.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)

main_example(ReducedWongWangExcIOInhI, RedWWExcIOInhIBuilder, InterfaceRedWWexcIOinhIBuilder,
             nest_nodes_ids, nest_populations_order=100, connectivity=connectivity,
             simulation_length=50.0, exclusive_nodes=True, config=config)
Esempio n. 5
0
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
# Some extra monitors for neuroimaging measures:
mon_raw = Raw(period=simulator.integrator.dt)
simulator.monitors = (mon_raw, )  # mon_bold, mon_eeg
Esempio n. 6
0
                               tvb_state_variables_labels=simulator.model.
                               variables_of_interest,
                               plot_per_neuron=False,
                               plotter=plotter,
                               config=config)
        except Exception as e:
            print("Error in plotting or writing to files!:\n%s" % str(e))

    return tvb_results, simulator


if __name__ == "__main__":
    # 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, label in enumerate(connectivity.region_labels):
        if label.find("cereb") > 0:
            nest_nodes_ids.append(id)

    if len(nest_nodes_ids) == 0:
        nest_nodes_ids = [
            0
        ]  # if the connectivity doesn't have cerebellum, just set a region for testing
    tvb_model = ReducedWongWangExcIO  # ReducedWongWangExcIOInhI

    model_params = {}

    main_example(
        tvb_model,
        CerebBuilder,
Esempio n. 7
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
Esempio n. 8
0
#
"""
Demo script on how to use tvb-framework default read/write capabilities

.. moduleauthor:: Lia Domide <*****@*****.**>
"""

from tvb.core.neocom import h5
from tvb.adapters.datatypes.h5.connectivity_h5 import ConnectivityH5
from tvb.datatypes.connectivity import Connectivity

if __name__ == '__main__':
    from tvb.interfaces.command.lab import *

    # Read from a ZIP
    conn_ht = Connectivity.from_file()
    conn_ht.configure()

    # Store in a given folder the HasTraits entity
    PATH = "."
    h5.store_complete(conn_ht, PATH)

    # Reproduce the just written file name containing GUID
    file_name = h5.path_for(PATH, ConnectivityH5, conn_ht.gid)

    # Load back from a file name a HasTraits instance
    conn_back = h5.load(file_name)

    # Check that the loaded and written entities are correct
    assert conn_ht.number_of_regions == 76
    assert conn_ht.number_of_regions == conn_back.number_of_regions
Esempio n. 9
0
 class sim:
     integrator = integrator_
     connectivity = Connectivity.from_file()
     model = MontbrioPazoRoxin()
Esempio n. 10
0
def prepare_launch_default_simulation():
    config = Config(output_base="outputs/")
    config.SAVE_FLAG = False
    config.SHOW_FLAG = False
    config.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]
Esempio n. 11
0
 def _config_connectivity(self, test_simulator):
     test_simulator.connectivity = Connectivity.from_file()
     test_simulator.connectivity.configure()
     test_simulator.connectivity.set_idelays(test_simulator.integrator.dt)
     test_simulator.horizon = test_simulator.connectivity.idelays.max() + 1
Esempio n. 12
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
Esempio n. 13
0
def generate_region_demo_data(file_path=os.path.join(os.getcwd(), "demo_data_region_16s_2048Hz.npy")):
    """
    Generate 16 seconds of 2048Hz data at the region level, stochastic integration.

    ``Run time``: approximately 4 minutes (workstation circa 2010)

    ``Memory requirement``: < 1GB
    ``Storage requirement``: ~ 19MB

    .. moduleauthor:: Stuart A. Knock <*****@*****.**>

    """

    ##----------------------------------------------------------------------------##
    ##-                      Perform the simulation                              -##
    ##----------------------------------------------------------------------------##

    LOG.info("Configuring...")

    # Initialise a Model, Coupling, and Connectivity.
    pars = {'a': np.array([1.05]),
            'b': np.array([-1]),
            'c': np.array([0.0]),
            'd': np.array([0.1]),
            'e': np.array([0.0]),
            'f': np.array([1 / 3.]),
            'g': np.array([1.0]),
            'alpha': np.array([1.0]),
            'beta': np.array([0.2]),
            'tau': np.array([1.25]),
            'gamma': np.array([-1.0])}

    oscillator = Generic2dOscillator(**pars)

    white_matter = Connectivity.from_file()
    white_matter.speed = np.array([4.0])
    white_matter_coupling = Linear(a=np.array([0.033]))

    # Initialise an Integrator
    hiss = Additive(nsig=np.array([2 ** -10, ]))
    heunint = HeunStochastic(dt=0.06103515625, noise=hiss)

    # Initialise a Monitor with period in physical time
    what_to_watch = TemporalAverage(period=0.48828125)  # 2048Hz => period=1000.0/2048.0

    # Initialise a Simulator -- Model, Connectivity, Integrator, and Monitors.
    sim = Simulator(model=oscillator, connectivity=white_matter,
                    coupling=white_matter_coupling,
                    integrator=heunint, monitors=[what_to_watch])

    sim.configure()

    # Perform the simulation
    tavg_data = []
    tavg_time = []
    LOG.info("Starting simulation...")
    for tavg in sim(simulation_length=16000):
        if tavg is not None:
            tavg_time.append(tavg[0][0])  # TODO:The first [0] is a hack for single monitor
            tavg_data.append(tavg[0][1])  # TODO:The first [0] is a hack for single monitor

    LOG.info("Finished simulation.")

    ##----------------------------------------------------------------------------##
    ##-                     Save the data to a file                              -##
    ##----------------------------------------------------------------------------##

    # Make the list a numpy.array.
    LOG.info("Converting result to array...")
    TAVG = np.array(tavg_data)

    # Save it
    LOG.info("Saving array to %s..." % file_path)
    np.save(file_path, TAVG)

    LOG.info("Done.")