def from_file(cls, source_file="cortex_16384.zip", region_mapping_file=os.path.join("regionMapping_16k_76.txt"), local_connectivity_file=None, eeg_projection_file=None, instance=None): result = super(Cortex, cls).from_file(source_file, instance) if instance is not None: # Called through constructor directly if result.region_mapping is None: result.region_mapping_data = RegionMapping.from_file() if not result.eeg_projection: result.eeg_projection = Cortex.from_file_projection_array() if result.local_connectivity is None: result.local_connectivity = LocalConnectivity.from_file() if region_mapping_file is not None: result.region_mapping_data = RegionMapping.from_file(region_mapping_file) if local_connectivity_file is not None: result.local_connectivity = LocalConnectivity.from_file(local_connectivity_file) if eeg_projection_file is not None: result.eeg_projection = Cortex.from_file_projection_array(eeg_projection_file) return result
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.Connectivity(load_default=True) # NOTE: This is the default region mapping should consider changing the name. region_mapping = RegionMapping.from_file( source_file= "cortex_reg13/region_mapping/o52r00_irp2008_hemisphere_both_subcortical_false_regions_74.txt.bz2" ) else: white_matter = connectivity.Connectivity.from_file( source_file="connectivity_190.zip") region_mapping = RegionMapping.from_file( source_file= "cortex_reg13/region_mapping/o52r00_irp2008_hemisphere_both_subcortical_true_regions_190.txt.bz2" ) white_matter_coupling = coupling.Linear(a=coupling_strength) white_matter.speed = speed dynamics = model() if method[-10:] == "Stochastic": hisss = noise.Additive(nsig=numpy.array([2**-11])) integrator = eval("integrators." + method + "(dt=dt, noise=hisss)") else: integrator = eval("integrators." + method + "(dt=dt)") if surface_sim: local_coupling_strength = numpy.array([2**-10]) default_cortex = Cortex(load_default=True, region_mapping_data=region_mapping) default_cortex.coupling_strength = local_coupling_strength default_cortex.local_connectivity = LocalConnectivity( load_default=default_connectivity, surface=default_cortex) else: default_cortex = None # Order of monitors determines order of returned values. self.sim = simulator.Simulator(model=dynamics, connectivity=white_matter, coupling=white_matter_coupling, integrator=integrator, monitors=self.monitors, surface=default_cortex) self.sim.configure()
def setup_method(self): 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), ) local_coupling_strength = numpy.array([2**-10]) region_mapping = RegionMapping.from_file('regionMapping_16k_%d.txt' % (self.n_regions, )) default_cortex = Cortex(region_mapping_data=region_mapping, load_default=True) default_cortex.coupling_strength = local_coupling_strength self.sim = simulator.Simulator(model=oscillator, connectivity=white_matter, coupling=white_matter_coupling, integrator=heunint, monitors=mons, surface=default_cortex) self.sim.configure()
def setup_method(self): self.sim = simulator.Simulator( connectivity=connectivity.Connectivity.from_file( 'connectivity_192.zip'), monitors=(monitors.iEEG( sensors=SensorsInternal(load_default=True), region_mapping=RegionMapping.from_file( 'regionMapping_16k_192.txt')))).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 from_file(cls, sensors_fname, projection_fname, rm_f_name="regionMapping_16k_76.txt", period=1e3/1024.0, **kwds): """ Build Projection-based monitor from sensors and projection files, and any extra keyword arguments are passed to the monitor class constructor. """ result = cls(period=period, **kwds) result.sensors = cls.sensors.field_type.from_file(sensors_fname) result.projection = cls.projection_class().from_file(projection_fname) result.region_mapping = RegionMapping.from_file(rm_f_name) return result
def test_gain_size(self): sim = simulator.Simulator( connectivity=connectivity.Connectivity.from_file('connectivity_192.zip'), monitors=(monitors.iEEG( sensors=SensorsInternal.from_file(), region_mapping=RegionMapping.from_file('regionMapping_16k_192.txt') ),) ).configure() ieeg = sim.monitors[0] # type: SensorsInternal n_sens, n_reg = ieeg.gain.shape assert ieeg.sensors.locations.shape[0] == n_sens assert sim.connectivity.number_of_regions == n_reg
def from_file( cls, source_file=os.path.join("cortex_reg13", "surface_cortex_reg13.zip"), region_mapping_file=os.path. join( "cortex_reg13", "region_mapping", "o52r00_irp2008_hemisphere_both_subcortical_false_regions_74.txt.bz2" ), local_connectivity_file=None, eeg_projection_file=None, instance=None): result = super(Cortex, cls).from_file(source_file, instance) if instance is not None: # Called through constructor directly if result.region_mapping is None: result.region_mapping_data = RegionMapping.from_file() if not result.eeg_projection: result.eeg_projection = Cortex.from_file_projection_array() if result.local_connectivity is None: result.local_connectivity = LocalConnectivity.from_file() if region_mapping_file is not None: result.region_mapping_data = RegionMapping.from_file( region_mapping_file) if local_connectivity_file is not None: result.local_connectivity = LocalConnectivity.from_file( local_connectivity_file) if eeg_projection_file is not None: result.eeg_projection = Cortex.from_file_projection_array( eeg_projection_file) return result
def from_file(cls, sensors_fname, projection_fname, rm_f_name="regionMapping_16k_76.txt", period=1e3/1024.0, instance=None, **kwds): """ Build Projection-based monitor from sensors and projection files, and any extra keyword arguments are passed to the monitor class constructor. """ if instance is None: result = cls(**kwds) else: result = instance result.sensors = type(cls.sensors).from_file(sensors_fname) result.projection = cls._projection_class().from_file(projection_fname) result.region_mapping = RegionMapping.from_file(rm_f_name) return result
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 test_regionmapping(self): dt = RegionMapping.from_file() assert isinstance(dt, RegionMapping) assert dt.array_data.shape == (16384, )
region_mapping_file=region_fname, eeg_projection_file=eeg_fname) ctx.configure() print("cortex loaded") pyplot.figure() ax = pyplot.subplot(111, projection='3d') x, y, z = ctx.vertices.T ax.plot_trisurf(x, y, z, triangles=ctx.triangles, alpha=0.1, edgecolor='k') # pyplot.show() print("cortex plot ready") # unit vectors that describe the location of eeg sensors sensoreeg_fname = os.path.join(master_path, 'DH_20120806_EEGLocations.txt') rm = RegionMapping.from_file(region_fname) sensorsEEG = SensorsEEG.from_file(sensoreeg_fname) prEEG = ProjectionSurfaceEEG.from_file(eeg_fname) fsamp = 1e3 / 1024.0 # 1024 Hz mon = monitors.EEG(sensors=sensorsEEG, projection=prEEG, 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
def __init__(self,Ps): """ Initialize simulation ---------------------- """ sim_length = Ps['sim_params']['length'] outdir = Ps['sim_params']['outdir'] if not os.path.isdir(outdir): os.mkdir(outdir) print '\nConfiguring sim...' sim = simulator.Simulator() _classes = [models, connectivity, coupling, integrators, monitors ] _names = ['model', 'connectivity', 'coupling', 'integrator', 'monitors'] for _class,_name in zip(_classes,_names): if _name is 'monitors': thisattr = tuple([getattr(_class,m['type'])(**m['params']) for m in Ps['monitors'] ]) else: if 'type' in Ps[_name]: thisattr = getattr(_class,Ps[_name]['type'])(**Ps[_name]['params']) setattr(sim,_name,thisattr) # Additionals - parameters that are functions of other classes # (example = larter_breakdspear demo) if 'additionals' in Ps: for a in Ps['additionals']: setattr(eval(a[0]), a[1],eval(a[2])) #sim,eval(a[0]),eval(a[1])) # Stochastic integrator if 'HeunStochastic' in Ps['integrator']: from tvb.simulator.lab import noise hiss = noise.Additive(nsig=np.array(Ps['integrator']['stochastic_nsig'])) # nsigm 0.015 sim.integrator.noise = hiss # Non-default connectivity # (to add here: # - load from other data structures, e.g. .cff file # - load weights, lengths, etc. directly from data matrices etc if 'connectivity' in Ps: if 'folder_path' in Ps['connectivity']: # (this is from the deterministic_stimulus demo) sim.connectivity.default.reload(sim.connectivity, Ps['connectivity']['folder_path']) sim.connectivity.configure() # EEG projections # (need to do this separately because don't seem to be able to do EEG(projection_matrix='<file>') for m_it, m in enumerate(Ps['monitors']): # (yes I know enumerate isn't necessary here; but it's more transparent imho) # assumption here is that the sim object doesn't re-order the list of monitors for any bizarre reason... # (which would almost certainly cause an error anyway...) #if m['type'] is 'EEG' and 'proj_mat_path' in m: # proj_mat = loadmat(m['proj_mat_path'])['ProjectionMatrix'] # pr = projections.ProjectionRegionEEG(projection_data=proj_mat) # sim.monitors[m_it].projection_matrix_data=pr if m['type'] is 'EEG': if m['proj_surf'] is 'default': pr = ProjectionSurfaceEEG(load_default=True) else: pr = ProjectionSurfaceEEG.from_file(m['proj_surf']) eeg_sens = SensorsEEG.from_file(source_file=m['source_file']) if m['reg_map'] is 'default': rm = RegionMapping(load_default=True) else: rm = RegionMapping.from_file(m['reg_map']) sim.monitors[m_it].projection = pr sim.monitors[m_it].sensors = eeg_sens sim.monitors[m_it].region_mapping = rm # Surface if 'surface' in Ps: surf = getattr(surfaces,Ps['surface']['surface_type']).default() if 'local_connectivity_params' in Ps['surface']: localsurfconn = getattr(surfaces,'LocalConnectivity')(**Ps['surface']['local_connectivity_params']) for ep in Ps['surface']['local_connectivity_equation_params'].items(): localsurfconn.equation.parameters[ep[0]] = ep[1] surf.local_connectivity = localsurfconn localcoupling = np.array( Ps['surface']['local_coupling_strength'] ) surf.coupling_strength = localcoupling sim.surface = surf # Stimulus if 'stimulus' in Ps: stim = getattr(patterns,Ps['stimulus']['type'])() if 'equation' in Ps['stimulus']: # looks like need to do this to keep the other params as default; slightly different to above stim_eqn_params = Ps['stimulus']['equation']['params'] # use this if need to evaluate text # (stim_eqn_params = {p[0]: eval(p[1]) for p in Ps['stimulus']['equation']['params'].items() } ( stim_eqn_t = getattr(equations,Ps['stimulus']['equation']['type'])() stim_eqn_t.parameters.update(**stim_eqn_params) stim.temporal = stim_eqn_t elif 'equation' not in Ps['stimulus']: # (still need to do this...) print 'something to do here' sim.connectivity.configure() stim_weighting = np.zeros((sim.connectivity.number_of_regions,)) stim_weighting[Ps['stimulus']['nodes']] = np.array(Ps['stimulus']['node_weightings']) stim.connectivity = sim.connectivity stim.weight = stim_weighting sim.stimulus = stim # Configure sim sim.configure() # Configure smooth parameter variation (if used) spv = {} if 'smooth_pvar' in Ps: par_length = eval(Ps['smooth_pvar']['par_length_str']) spv['mon_type'] = Ps['smooth_pvar']['monitor_type'] spv['mon_num'] = [m_it for m_it, m in enumerate(Ps['monitors']) if m == spv['mon_type'] ] # (yes, a bit clumsy..) # a) as an equally spaced range if 'equation' not in Ps['smooth_pvar']: spv['a'] = eval(Ps['smooth_pvar']['spv_a_str']) # b) using an Equation datadtype else: spv['params'] = {} for p in Ps['smooth_pvar']['equation']['params'].items(): spv['params'][p[0]] = eval(p[1]) #sim_length = Ps['sim_params']['length'] # temporary fix] #spv_a_params = {p[0]: eval(p[1]) for p in Ps['smooth_pvar']['equation']['params'].items() } spv['eqn_t'] = getattr(equations,Ps['smooth_pvar']['equation']['type'])() spv['eqn_t'].parameters.update(**spv['params']) spv['pattern'] = eval(Ps['smooth_pvar']['equation']['pattern_str']) spv['a'] = spv['pattern'] # omit above line? At moment this follows tutorial code # recent additions.... self.sim = sim self.Ps = Ps self.sim_length = sim_length self.spv = spv
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()
oscillator = models.Generic2dOscillator() white_matter = connectivity.Connectivity.from_file('connectivity_192.zip') white_matter.speed = numpy.array([4.0]) white_matter_coupling = coupling.Difference(a=0.014) heunint = integrators.HeunStochastic( dt=2**-4, noise=noise.Additive(nsig=numpy.array([2 ** -10, ])) ) fsamp = 1e3/1024.0 # 1024 Hz monitors = ( monitors.EEG.from_file('eeg-brainstorm-65.txt', 'projection_EEG_surface.npy', period=fsamp), monitors.MEG.from_file('meg-brainstorm-276.txt', 'projection_MEG_surface.npy', period=fsamp), monitors.iEEG.from_file('SEEG_588.txt', 'projection_SEEG_surface.npy', period=fsamp), ) local_coupling_strength = numpy.array([2 ** -10]) default_cortex = Cortex(region_mapping_data=RegionMapping.from_file('regionMapping_16k_192.txt'), load_default=True) default_cortex.coupling_strength = local_coupling_strength sim = simulator.Simulator(model=oscillator, connectivity=white_matter, coupling=white_matter_coupling, integrator=heunint, monitors=monitors, surface=default_cortex) sim.configure() ts, ys = {}, {} mons = 'eeg meg seeg'.split() for key in mons: ts[key] = [] ys[key] = [] for data in sim(simulation_length=2**2):