def build_and_run_(spec): """ Builds a simulator from spec, run & collect output. Returns an HDF5 file with the results. """ opt = spec['opt'] print "pool starting ", opt # lenght of simulation tf = float(opt.get('tf', 100)) # model # coupling function # connectivity simargs = {} for mod, key in [(models, 'model'), (connectivity, 'connectivity'), (coupling, 'coupling')]: simargs[key] = build_sim_part(mod, opt[key]) # noise # integrator optint = opt['integrator'] if 'noise' in optint: optint['noise'] = build_sim_part(noise, optint['noise']) simargs['integrator'] = build_sim_part(integrators, optint) # monitors if not type(opt['monitors']) in (list, ): opt['monitors'] = [opt['monitors']] simargs['monitors'] = [] for mon in opt['monitors']: simargs['monitors'].append(build_sim_part(monitors, mon)) # stimulus # NotImplemented # simulator sim = simulator.Simulator(**simargs) sim.configure() # TODO open HDF5 first, figure out correct sizes, etc # loop, writing data to h5 ts = [[] for _ in opt['monitors']] ys = [[] for _ in opt['monitors']] for i, all_monitor_data in enumerate(sim(tf)): for j, mondata in enumerate(all_monitor_data): if not mondata is None: t, y = mondata ts[j].append(t) ys[j].append(y) # write data to hdf5 file path = os.path.abspath(opt.get('wd', './')) h5fname = os.path.join(path, "tvb_%s.h5" % (spec['md5sum'], )) h5 = h5py.File(h5fname, 'w') for i, (mon, (t, y)) in enumerate(zip(simargs['monitors'], zip(ts, ys))): mname = "mon_%d_%s" % (i, mon.__class__.__name__) g = h5.create_group(mname) g.create_dataset('ts', data=t) g.create_dataset('ys', data=y) h5.close() # return filename print "pool finished", opt return h5fname
eqn_x.parameters["amp"] = -0.0625 eqn_x.parameters["sigma"] = 28.0 stimulus = patterns.StimuliSurface( surface= default_cortex, #TODO: This is required because UI requires the surface associated with the Stimuli temporal=eqn_t, spatial=eqn_x, focal_points_surface=numpy.array([8000])) #Initialise Simulator -- Model, Connectivity, Integrator, Monitors, and surface. sim = simulator.Simulator(model=oscilator, connectivity=white_matter, coupling=white_matter_coupling, integrator=heunint, monitors=what_to_watch, surface=default_cortex, stimulus=stimulus) sim.configure() #Clear the initial transient, so that the effect of the stimulus is clearer. #NOTE: this is ignored, stimuli are defined relative to each simulation call. LOG.info("Initial integration to clear transient...") for _, _, _ in sim(simulation_length=128): pass import time tic = time.time()
#Initialise an Integrator adding noise to only one state variable hiss = noise.Additive(nsig=numpy.array([0., 0., 0., 0., nsigma, 0.])) heunint = integrators.HeunStochastic(dt=2**-4, noise=hiss) #Initialise some Monitors with period in physical time momo = monitors.Raw() mama = monitors.TemporalAverage(period=2**-2) #Bundle them what_to_watch = list((momo, mama)) #Initialise Simulator -- Model, Connectivity, Integrator, Monitors, and stimulus. sim = simulator.Simulator(model=jrm, connectivity=white_matter, coupling=white_matter_coupling, integrator=heunint, monitors=what_to_watch) sim.configure() LOG.info("Starting simulation...") #Perform the simulation raw_data = [] raw_time = [] tavg_time = [] tavg_data = [] for raw, tavg in sim(simulation_length=2**10): if not raw is None: raw_time.append(raw[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()
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()
def test_surface_sim_with_projections(self): # Setup Simulator obj oscillator = models.Generic2dOscillator() white_matter = connectivity.Connectivity.from_file( 'connectivity_%d.zip' % (self.n_regions, )) white_matter.speed = numpy.array([self.speed]) white_matter_coupling = coupling.Difference(a=self.coupling_a) heunint = integrators.HeunStochastic( dt=2**-4, noise=noise.Additive(nsig=numpy.array([ 2**-10, ]))) mons = ( monitors.EEG.from_file(period=self.period), monitors.MEG.from_file(period=self.period), # monitors.iEEG.from_file(period=self.period), # SEEG projection data is not part of tvb-data on Pypi, thus this can not work generic ) local_coupling_strength = numpy.array([2**-10]) region_mapping = RegionMapping.from_file('regionMapping_16k_%d.txt' % (self.n_regions, )) region_mapping.surface = CorticalSurface.from_file() default_cortex = Cortex.from_file() default_cortex.region_mapping_data = region_mapping default_cortex.coupling_strength = local_coupling_strength sim = simulator.Simulator(model=oscillator, connectivity=white_matter, coupling=white_matter_coupling, integrator=heunint, monitors=mons, surface=default_cortex) sim.configure() # check configured simulation connectivity attribute conn = sim.connectivity assert conn.number_of_regions == self.n_regions assert conn.speed == self.speed # test monitor properties lc_n_node = sim.surface.local_connectivity.matrix.shape[0] for mon in sim.monitors: assert mon.period == self.period n_sens, g_n_node = mon.gain.shape assert g_n_node == sim.number_of_nodes assert n_sens == mon.sensors.number_of_sensors assert lc_n_node == g_n_node # check output shape ys = {} mons = 'eeg meg seeg'.split() for key in mons: ys[key] = [] for data in sim(simulation_length=3.0): for key, dat in zip(mons, data): if dat: _, y = dat ys[key].append(y) for mon, key in zip(sim.monitors, mons): ys[key] = numpy.array(ys[key]) assert ys[key].shape[2] == mon.gain.shape[0]
def config_simulation(self, hypothesis, head_connectivity, settings=SimulationSettings()): tvb_conn = self._vep2tvb_connectivity(head_connectivity) coupl = coupling.Difference(a=1.) # Set noise: if isinstance(settings.noise_preconfig, noise.Noise): integrator = integrators.HeunStochastic( dt=settings.integration_step, noise=settings.noise_preconfig) else: settings.noise_intensity = numpy.array(settings.noise_intensity) if settings.noise_intensity.size == 1: settings.noise_intensity = numpy.repeat( numpy.squeeze(settings.noise_intensity), self.model.nvar) if numpy.min(settings.noise_intensity) > 0: thisNoise = noise.Additive( nsig=settings.noise_intensity, random_stream=numpy.random.RandomState( seed=settings.noise_seed)) settings.noise_type = "Additive" integrator = integrators.HeunStochastic( dt=settings.integration_step, noise=thisNoise) else: integrator = integrators.HeunDeterministic( dt=settings.integration_step) settings.noise_type = "None" # Set monitors: what_to_watch = [] if isinstance(settings.monitors_preconfig, monitors.Monitor): what_to_watch = (settings.monitors_preconfig, ) elif isinstance(settings.monitors_preconfig, tuple) or isinstance( settings.monitors_preconfig, list): for monitor in settings.monitors_preconfig: if isinstance(monitor, monitors.Monitor): what_to_watch.append(monitor) what_to_watch = tuple(what_to_watch) # TODO: Find a better way to define monitor expressions without the need to modify the model... if settings.monitor_expressions is not None: self.model.variables_of_interest = settings.monitor_expressions # Create and configure TVB simulator object sim = simulator.Simulator(model=self.model, connectivity=tvb_conn, coupling=coupl, integrator=integrator, monitors=what_to_watch, simulation_length=settings.simulated_period) sim.configure() sim.initial_conditions = self.prepare_initial_conditions( hypothesis, sim.good_history_shape[0]) # Update simulation settings settings.integration_step = integrator.dt settings.simulated_period = sim.simulation_length settings.integrator_type = integrator._ui_name settings.noise_ntau = integrator.noise.ntau settings.noise_intensity = numpy.array(settings.noise_intensity) settings.monitor_type = what_to_watch[0]._ui_name # TODO: find a way to store more than one monitors settings settings.monitor_sampling_period = what_to_watch[0].period settings.monitor_expressions = self.model.variables_of_interest settings.initial_conditions = sim.initial_conditions return sim, settings
region_mapping=rm, period=fsamp) sim = simulator.Simulator( connectivity=conn, # conduction speed: 3 mm/ms # coupling: linear - rescales activity propagated # stimulus: None - can be a spatiotemporal function # model: Generic 2D Oscillator - neural mass has two state variables that # represent a neuron's membrane potential and recovery; see the # mathematics paper for default values and equations; runtime 8016 s model=Linear(), # model: Wilson & Cowan - two neural masses have an excitatory/inhibitory # relationship; see paper for details; runtime 16031 s # model: Wong & Wang - reduced system of two non-linear coupled differential # equations based on the attractor network model; see paper; runtime 8177 s # model: Jansen & Rit - biologically inspired mathematical framework # originally conceived to simulate the spontaneous electrical activity of # neuronal assemblies, with a particular focus on alpha activity; had # some weird numpy overflow errors, only generated ~200 ms data; runtime 5929 s # integrator=VODEStochastic(), # initial conditions: None monitors=mon, surface=ctx, simulation_length=5.0 # ms ).configure() print("sim configured") print("sim running")