Esempio n. 1
0
def configure_simulation(stimulate):
    """
    Set up a Simulator object (a brain network model and all its individual 
    components + output modalities)
    """
    # eeg projection matrix from regions to sensors
    LOG.info("Reading sensors info")

    pr = ProjectionSurfaceEEG(load_default=True)
    sensors = SensorsEEG.from_file(source_file="eeg_brainstorm_65.txt")
    rm = RegionMapping(load_default=True)

    #Initialise a Model, Connectivity, Coupling, set speed.
    oscilator = models.Generic2dOscillator(a=-0.5, b=-10., c=0.0, d=0.02)

    white_matter = connectivity.Connectivity(load_default=True)
    white_matter.speed = numpy.array([4.0])
    white_matter_coupling = coupling.Linear(a=0.042)

    #Initialise an Integrator
    hiss = noise.Additive(nsig=numpy.array([0.00]))  # nsigm 0.015
    heunint = integrators.HeunStochastic(dt=2**-6, noise=hiss)

    # Recording techniques
    what_to_watch = (monitors.TemporalAverage(period=1e3 / 4096.),
                     monitors.EEG(projection=pr,
                                  sensors=sensors,
                                  region_mapping=rm,
                                  period=1e3 / 4096.))
    # Stimulation paradigm
    if stimulate:
        stimulus = build_stimulus(white_matter)
    else:
        stimulus = None

    #Initialise a Simulator -- Model, Connectivity, Integrator, and Monitors.
    sim = simulator.Simulator(model=oscilator,
                              connectivity=white_matter,
                              coupling=white_matter_coupling,
                              integrator=heunint,
                              monitors=what_to_watch,
                              stimulus=stimulus)
    sim.configure()
    return sim
def configure_simulation(stimulate):
    """
    Set up a Simulator object (a brain network model and all its individual 
    components + output modalities)
    """
    # eeg projection matrix from regions to sensors
    LOG.info("Reading sensors info")

    pr = ProjectionSurfaceEEG(load_default=True)
    sensors = SensorsEEG.from_file(source_file="eeg_brainstorm_65.txt")
    rm = RegionMapping(load_default=True)

    #Initialise a Model, Connectivity, Coupling, set speed.
    oscilator = models.Generic2dOscillator(a=-0.5, b=-10., c=0.0, d=0.02)

    white_matter = connectivity.Connectivity(load_default=True)
    white_matter.speed = numpy.array([4.0])
    white_matter_coupling = coupling.Linear(a=0.042)

    #Initialise an Integrator
    hiss = noise.Additive(nsig=numpy.array([0.00]))  # nsigm 0.015
    heunint = integrators.HeunStochastic(dt=2 ** -6, noise=hiss)

    # Recording techniques
    what_to_watch = (monitors.TemporalAverage(period=1e3 / 4096.),
                     monitors.EEG(projection=pr, sensors=sensors, region_mapping=rm, period=1e3 / 4096.))
    # Stimulation paradigm
    if stimulate:
        stimulus = build_stimulus(white_matter)
    else:
        stimulus = None

    #Initialise a Simulator -- Model, Connectivity, Integrator, and Monitors.
    sim = simulator.Simulator(model=oscilator, connectivity=white_matter, coupling=white_matter_coupling,
                              integrator=heunint, monitors=what_to_watch, stimulus=stimulus)
    sim.configure()
    return sim
Esempio n. 3
0
                              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

    # model: Generic 2D Oscillator - neural mass has two state variables that
Esempio n. 4
0
  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
Esempio n. 5
0
 def from_tvb_file(self, filepath, remove_leading_zeros_from_labels=False):
     self._tvb = TVBSensorsEEG.from_file(filepath, self._tvb)
     if len(self._tvb.labels) > 0:
         if remove_leading_zeros_from_labels:
             self.remove_leading_zeros_from_labels()
     return self