cell_parameters = { 'morphology' : join('cells', 'cells', 'j4a.hoc'), # from Mainen & Sejnowski, J Comput Neurosci, 1996 'cm' : 1.0, # membrane capacitance 'Ra' : 150., # axial resistance 'v_init' : -65., # initial crossmembrane potential 'passive' : True, # turn on NEURONs passive mechanism for all sections 'passive_parameters' : {'g_pas' : 1./30000, 'e_pas' : -65}, 'nsegs_method' : 'lambda_f', # spatial discretization method 'lambda_f' : 100., # frequency where length constants are computed 'dt' : 2.**-3, # simulation time step size 'tstart' : 0., # start time of simulation, recorders start at t=0 'tstop' : 100., # stop simulation at 100 ms. } # Create cell cell = LFPy.Cell(**cell_parameters) # Align cell cell.set_rotation(x=4.99, y=-4.33, z=3.14) # Define synapse parameters synapse_parameters = { 'idx' : cell.get_closest_idx(x=-200., y=0., z=800.), 'e' : 0., # reversal potential 'syntype' : 'ExpSyn', # synapse type 'tau' : 5., # synaptic time constant 'weight' : .001, # synaptic weight 'record_current' : True, # record synapse current } # Create synapse and set time of synaptic input synapse = LFPy.Synapse(cell, **synapse_parameters)
def return_extracellular_spike(cell, cell_name, model_type, electrode_parameters, limits, rotation, pos=None): """ Calculate extracellular spike on MEA at random position relative to cell Parameters: ----------- cell: object cell object from LFPy cell_name: string name of cell model electrode_parameters: dict parameters to initialize LFPy.RecExtElectrode limits: array_like boundaries for neuron locations, shape=(3,2) rotation: string random rotation to apply to the neuron ('Norot', '3drot', 'physrot') pos: array_like, (optional, default None) Can be used to set the cell soma to a specific position. If ``None``, the random position is used. Returns: -------- Extracellular spike for each MEA contact site """ import LFPy def get_xyz_angles(R): """ Get rotation angles for each axis from rotation matrix Parameters; ----------- R : matrix 3x3 rotation matrix Returns: -------- R_z : float R_y : float R_x : float Three angles for rotations around axis, defined by R = R_z.R_y.R_x """ rot_x = np.arctan2(R[2, 1], R[2, 2]) rot_y = np.arcsin(-R[2, 0]) rot_z = np.arctan2(R[1, 0], R[0, 0]) return rot_x, rot_y, rot_z def get_rnd_rot_Arvo(): """ Generate uniformly distributed random rotation matrices see: 'Fast Random Rotation Matrices' by Arvo (1992) Returns: -------- R : 3x3 matrix random rotation matrix """ gamma = np.random.uniform(0, 2. * np.pi) rotation_z = np.matrix([[np.cos(gamma), -np.sin(gamma), 0], [np.sin(gamma), np.cos(gamma), 0], [0, 0, 1]]) x = np.random.uniform(size=2) v = np.array([ np.cos(2. * np.pi * x[0]) * np.sqrt(x[1]), np.sin(2. * np.pi * x[0]) * np.sqrt(x[1]), np.sqrt(1 - x[1]) ]) H = np.identity(3) - 2. * np.outer(v, v) M = -np.dot(H, rotation_z) return M def check_solidangle(matrix, pre, post, polarlim): """ Check whether a matrix rotates the vector 'pre' into a region defined by 'polarlim' around the vector 'post' Parameters: ----------- matrix : matrix 3x3 rotation matrix pre : array_like 3-dim vector to be rotated post : array_like axis of the cones defining the post-rotation region polarlim : [float,float] Angles specifying the opening of the inner and outer cone (aperture = 2*polarlim), i.e. the angle between rotated pre vector and post vector has to ly within these polar limits. Returns: -------- test : bool True if the vector np.dot(matrix,pre) lies inside the specified region. """ postest = np.dot(matrix, pre) c = np.dot(post / np.linalg.norm(post), postest / np.linalg.norm(postest)) if np.cos(np.deg2rad(polarlim[1])) <= c <= np.cos( np.deg2rad(polarlim[0])): return True else: return False electrodes = LFPy.RecExtElectrode(cell, **electrode_parameters) """Rotate neuron""" if rotation == 'norot': if model_type == 'bbp': # orientate cells in z direction x_rot_offset = np.pi / 2. y_rot_offset = 0 z_rot_offset = 0 x_rot = x_rot_offset y_rot = y_rot_offset z_rot = z_rot_offset elif rotation == 'xrot': if model_type == 'bbp': # orientate cells in z direction x_rot_offset = np.pi / 2. y_rot_offset = 0 z_rot_offset = 0 x_rot, _, _ = get_xyz_angles(np.array(get_rnd_rot_Arvo())) x_rot = x_rot + x_rot_offset y_rot = y_rot_offset z_rot = z_rot_offset elif rotation == 'yrot': if model_type == 'bbp': # orientate cells in z direction x_rot_offset = np.pi / 2. y_rot_offset = 0 z_rot_offset = 0 _, y_rot, _ = get_xyz_angles(np.array(get_rnd_rot_Arvo())) x_rot = x_rot_offset y_rot = y_rot + y_rot_offset z_rot = z_rot_offset elif rotation == 'zrot': if model_type == 'bbp': # orientate cells in z direction x_rot_offset = np.pi / 2. y_rot_offset = 0 z_rot_offset = 0 _, _, z_rot = get_xyz_angles(np.array(get_rnd_rot_Arvo())) x_rot = x_rot_offset y_rot = y_rot_offset z_rot = z_rot + z_rot_offset elif rotation == '3drot': if model_type == 'bbp': x_rot_offset = np.pi / 2. # align neuron with z axis y_rot_offset = 0 # align neuron with z axis z_rot_offset = 0 # align neuron with z axis x_rot, y_rot, z_rot = get_xyz_angles(np.array(get_rnd_rot_Arvo())) x_rot = x_rot + x_rot_offset y_rot = y_rot + y_rot_offset z_rot = z_rot + z_rot_offset elif rotation == 'physrot': polarlim, pref_orient = get_physrot_specs(cell_name, model_type) if model_type == 'bbp': x_rot_offset = np.pi / 2. # align neuron with z axis y_rot_offset = 0 # align neuron with z axis z_rot_offset = 0 # align neuron with z axis while True: R = np.array(get_rnd_rot_Arvo()) if polarlim is None or pref_orient is None: valid = True else: valid = check_solidangle(R, [0., 0., 1.], pref_orient, polarlim) if valid: x_rot, y_rot, z_rot = get_xyz_angles(R) x_rot = x_rot + x_rot_offset y_rot = y_rot + y_rot_offset z_rot = z_rot + z_rot_offset break else: rotation = None x_rot = 0 y_rot = 0 z_rot = 0 if pos is None: """Move neuron randomly""" x_rand = np.random.uniform(limits[0][0], limits[0][1]) y_rand = np.random.uniform(limits[1][0], limits[1][1]) z_rand = np.random.uniform(limits[2][0], limits[2][1]) cell.set_pos(x_rand, y_rand, z_rand) pos = [x_rand, y_rand, z_rand] else: cell.set_pos(pos[0], pos[1], pos[2]) cell.set_rotation(x=x_rot, y=y_rot, z=z_rot) rot = [x_rot, y_rot, z_rot] electrodes.calc_lfp() # Reverse rotation to bring cell back into initial rotation state if rotation is not None: rev_rot = [-r for r in rot] cell.set_rotation(rev_rot[0], rev_rot[1], rev_rot[2], rotation_order='zyx') return 1000 * electrodes.LFP, pos, rot, electrodes.offsets
def test_Network_00(self): cellParameters = dict( morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks_w_lists.hoc'), templatefile=os.path.join(LFPy.__path__[0], 'test', 'ball_and_stick_template.hoc'), templatename='ball_and_stick_template', templateargs=None, passive=False, dt=2**-3, tstop=100, delete_sections=False, ) populationParameters = dict( CWD=None, CELLPATH=None, Cell=LFPy.NetworkCell, cell_args=cellParameters, pop_args=dict(radius=100, loc=0., scale=20.), rotation_args=dict(x=0, y=0), POP_SIZE=4, name='test', ) networkParameters = dict(dt=2**-3, tstart=0., tstop=100., v_init=-65., celsius=6.3, OUTPUTPATH='tmp_testNetworkPopulation') # set up network = LFPy.Network(**networkParameters) network.create_population(**populationParameters) connectivity = network.get_connectivity_rand(pre='test', post='test', connprob=0.5) # test set up for population in network.populations.values(): self.assertTrue(len(population.cells) == population.POP_SIZE) for cell, soma_pos, gid in zip(population.cells, population.soma_pos, population.gids): self.assertTrue(type(cell) is LFPy.NetworkCell) self.assertTrue((cell.somapos[0] == soma_pos['x']) & (cell.somapos[1] == soma_pos['y']) & (cell.somapos[2] == soma_pos['z'])) self.assertEqual(cell.gid, gid) self.assertTrue( np.sqrt(soma_pos['x']**2 + soma_pos['y']**2) <= 100.) np.testing.assert_equal(population.gids, np.arange(4)) np.testing.assert_equal(connectivity.shape, (population.POP_SIZE, population.POP_SIZE)) np.testing.assert_equal(connectivity.diagonal(), np.zeros(population.POP_SIZE)) # connect and run sim network.connect(pre='test', post='test', connectivity=connectivity) network.simulate() # test output for population in network.populations.values(): for cell in population.cells: self.assertTrue(np.all(cell.somav == network.v_init)) network.pc.gid_clear() os.system('rm -r tmp_testNetworkPopulation') neuron.h('forall delete_section()')
'custom_code': custom_code } COMM.Barrier() # names = ["axon myelin", "neuron myelin", "neuron nonmyelin", "axon nonmyelin"] names = [ "Horiz axon myelin long", "Horiz axon myelin", "Vert axon myelin", "Vert soma + axon myelin", "Horiz axon unmyelin long", "Horiz axon unmyelin", "Vert axon unmyelin", "Vert soma + axon unmyelin" ] # names = ["Layer I parallel myelin", "neuron myelin", "neuron unmyelin", "axon unmyelin"] clamp = False cell = LFPy.Cell(**cell_parameters) # Assign cell positions # TEST with different distance between cells # x_cell_pos = [-10, 0, 0, 10] # y_cell_pos = [0, -10, 10, 0] x_cell_pos = np.zeros(n_cells) y_cell_pos = np.linspace(-50, 50, n_cells) # z_cell_pos = np.zeros(len(x_cell_pos)) z_ratio = np.ones(n_cells) * -1. z_cell_pos_init = np.multiply(np.ones(len(x_cell_pos)), z_ratio) z_cell_pos = z_cell_pos_init # z_cell_pos = np.ones(n_cells) # z_cell_pos_init = np.ones(n_cells) # z_cell_pos = [-1000., -1000 - (np.sum(cell.length)), 0.] # xrot = [0., 2., 1.]
def calculate_extracellular_potential(cell, mea, ncontacts=10, position=None, rotation=None): ''' Calculates extracellular signal in uV on MEA object. Parameters ---------- cell : LFPy Cell The simulated cell mea : MEA, str, or dict Mea object from MEAutility, string with probe name, or dict with probe info Returns ------- v_ext : np.array Extracellular potential computed on the electrodes (n_elec, n_timestamps) ''' import LFPy if isinstance(mea, str): mea_obj = mu.return_mea(mea) elif isinstance(mea, dict): mea_obj = mu.return_mea(info=mea) elif isinstance(mea, mu.core.MEA): mea_obj = mea else: raise Exception("") pos = mea_obj.positions elinfo = mea_obj.info elec_x = pos[:, 0] elec_y = pos[:, 1] elec_z = pos[:, 2] N = np.empty((pos.shape[0], 3)) for i in np.arange(N.shape[0]): N[i] = [1, 0, 0] # normal vec. of contacts # Add square electrodes (instead of circles) if ncontacts > 1: electrode_parameters = { 'sigma': 0.3, # extracellular conductivity 'x': elec_x, # x,y,z-coordinates of contact points 'y': elec_y, 'z': elec_z, 'n': ncontacts, 'r': elinfo['size'], 'N': N, 'contact_shape': elinfo['shape'] } else: electrode_parameters = { 'sigma': 0.3, # extracellular conductivity 'x': elec_x, # x,y,z-coordinates of contact points 'y': elec_y, 'z': elec_z } electrodes = LFPy.RecExtElectrode(cell, **electrode_parameters) if position is not None: assert len(position) == 3, "'position' should be a 3d array" cell.set_pos(position[0], position[1], position[2]) if rotation is not None: assert len(rotation) == 3, "'rotation' should be a 3d array" cell.set_rotation(x=rotation[0], y=rotation[1], z=rotation[2]) electrodes.calc_lfp() # Reverse rotation to bring cell back into initial rotation state if rotation is not None: rev_rot = [-r for r in rotation] cell.set_rotation(rev_rot[0], rev_rot[1], rev_rot[2], rotation_order='zyx') return 1000 * electrodes.LFP
cell_params = { 'morphology': 'morphologies/L5_Mainen96_LFPy.hoc', 'tstart': 0., 'tstop': 40 } synapse_params = { 'e': 0., # reversal potential 'syntype': 'ExpSyn', # exponential synapse 'tau': 5., # synapse time constant 'weight': 0.001, # 0.001, # synapse weight 'record_current': True # record synapse current } # create cell with parameters in dictionary cell = LFPy.Cell(**cell_params) pos = syn_loc synapse_params['idx'] = cell.get_closest_idx(x=pos[0], y=pos[1], z=pos[2]) synapse = LFPy.Synapse(cell, **synapse_params) synapse.set_spike_times(np.array([5.])) cell.simulate(rec_imem=True, rec_current_dipole_moment=True) # compute dipole P = cell.current_dipole_moment somapos = np.array([0., 0., 77500]) r_soma_syns = [ cell.get_intersegment_vector(idx0=0, idx1=i) for i in cell.synidx ] r_mid = np.average(r_soma_syns, axis=0)
neuron.h.load_file(1, "biophysics.hoc") if not hasattr(neuron.h, synapses): # load synapses neuron.h.load_file(1, posixpth(os.path.join('synapses', 'synapses.hoc'))) if not hasattr(neuron.h, templatename): # Load main cell template neuron.h.load_file(1, "template.hoc") for morphologyfile in glob(os.path.join('morphology', '*')): if COUNTER % SIZE == RANK: # Instantiate the cell(s) using LFPy cell = LFPy.TemplateCell(morphology=morphologyfile, templatefile=posixpth( os.path.join(NRN, 'template.hoc')), templatename=templatename, templateargs=1 if add_synapses else 0, tstop=tstop, dt=dt, nsegs_method=None) #set view as in most other examples cell.set_rotation(x=np.pi / 2) pointProcess = LFPy.StimIntElectrode(cell, **PointProcParams) electrode = LFPy.RecExtElectrode(x=np.array([-40, 40., 0, 0]), y=np.array([0, 0, -40, 40]), z=np.zeros(4), sigma=0.3, r=5, n=50,
for model_idx in range(len(all_models)): model_name = all_models[model_idx] #print(model_idx, model_name) model_folder = join("cell_models", model_name) cell = return_allen_cell_model(model_folder) pointprocess = { 'idx': 0, 'record_current': True, 'pptype': 'IClamp', 'amp': iamp, 'dur': idur, 'delay': 1, } stimulus = LFPy.StimIntElectrode(cell, **pointprocess) cell.simulate(rec_vmem=True, rec_variables=['cai']) #idxs = cell.get_idx(section="axon") plt.close("all") fig = plt.figure(figsize=[12, 8]) fig.subplots_adjust(wspace=0.5) ax1 = fig.add_subplot(231, aspect=1, xlabel="x", ylabel="z") ax2 = fig.add_subplot(234, aspect=1, xlabel="x", ylabel="y") ax3 = fig.add_subplot(132) ax4 = fig.add_subplot(133, ylabel="nA") [ ax1.plot([cell.xstart[idx], cell.xend[idx]], [cell.zstart[idx], cell.zend[idx]],
for popName in dipole_names: dipole_recorders[popName] = [] for cell in getattr(h, popName): for dipole in cell.bd: dipole_recorders[popName].append(h.Vector().record( dipole._ref_Qsum)) # Define grid recording electrode gridLims = {'x': [-400, 1100], 'y': [-300, 1400]} X, Y = np.mgrid[gridLims['x'][0]:gridLims['x'][1]:25, gridLims['y'][0]:gridLims['y'][1]:25] Z = np.zeros(X.shape) grid_electrode = LFPy.RecExtElectrode( **{ 'sigma': 0.3, # extracellular conductivity 'x': X.flatten(), # electrode requires 1d vector of positions 'y': Y.flatten(), 'z': Z.flatten() }) # ---------------------------------------------------- # Run model! # ---------------------------------------------------- h('run()') # ---------------------------------------------------- # Create dummy cell and LFP/dipole information # ---------------------------------------------------- # Get segment positions in xyz space xyz_starts, xyz_ends = np.zeros(shape=(0, 3)), np.zeros(shape=(0, 3))
#define parameters for extracellular recording electrode, using optional method electrodeParameters = { 'sigma': 0.3, # extracellular conductivity 'x': X.flatten(), # x,y,z-coordinates of contact points 'y': Y.flatten(), 'z': Z.flatten(), 'method': 'soma_as_point', #treat soma segment as sphere source } ################################################################################ # Main simulation procedure, setting up extracellular electrode, cell, synapse ################################################################################ #create extracellular electrode object electrode = LFPy.RecExtElectrode(**electrodeParameters) #Initialize cell instance, using the LFPy.Cell class cell = LFPy.Cell(**cellParameters) #set the position of midpoint in soma to Origo (not needed, this is the default) cell.set_pos(x=0, y=0, z=0) #rotate the morphology 90 degrees around z-axis cell.set_rotation(z=np.pi / 2) #attach synapse with parameters and set spike time synapse = LFPy.Synapse(cell, **synapseParameters) synapse.set_spike_times(np.array([1])) #perform NEURON simulation, results saved as attributes in the cell instance cell.simulate(electrode=electrode)
def plotcell(cell, color='k'): for sec in cell.template.all: idx = cell.get_idx(sec.name()) plt.plot(np.r_[cell.xstart[idx], cell.xend[idx][-1]], np.r_[cell.zstart[idx], cell.zend[idx][-1]], color=color) print(' ') #delete cell instances from previous script executions, neuron.h('forall delete_section()') #create some cell instances, set the positions, plot the morphologies cell1 = LFPy.TemplateCell( morphology='morphologies/markram/CNG version/C010398B-P2.CNG.swc', templatefile='LFPyCellTemplate.hoc', templatename='LFPyCellTemplate', templateargs=None) cell1.set_pos(0) plotcell(cell=cell1, color='r') cell2 = LFPy.TemplateCell( morphology='morphologies/markram/Source-Version/C010398B-P2.asc', templatefile='LFPyCellTemplate.hoc', templatename='LFPyCellTemplate', templateargs=None) cell2.set_pos(200) plotcell(cell=cell2, color='g') cell3 = LFPy.TemplateCell(morphology='morphologies/L5_Mainen96_LFPy.hoc', templatefile='LFPyCellTemplate.hoc',
def return_cell(cell_name, sim_name): if cell_name == "hay": neuron.load_mechanisms(join('L5bPCmodelsEH', "mod")) cell_parameters = { 'morphology': join('L5bPCmodelsEH/morphologies/cell1.asc'), 'templatefile': [join('L5bPCmodelsEH/models/L5PCbiophys3.hoc'), join('L5bPCmodelsEH/models/L5PCtemplate.hoc')], 'templatename': 'L5PCtemplate', 'templateargs': join('L5bPCmodelsEH/morphologies/cell1.asc'), 'passive': False, 'nsegs_method': None, 'dt': 2**-6, 'tstart': -150, 'tstop': 50, 'v_init': -70, 'celsius': 34, 'pt3d': True, } cell = LFPy.TemplateCell(**cell_parameters) if "without_ca" in sim_name: remove_ca_mechanisms() make_cell_uniform(Vrest=-70) print("Removed calcium currents") elif "passive" in sim_name: remove_active_mechanisms() make_cell_uniform(Vrest=-70) print("Removed all active currents") else: print("Control simulation") make_cell_uniform(Vrest=-70) cell.set_rotation(x=4.729, y=-3.166) elif cell_name == "two_comp": h(""" proc celldef() { topol() subsets() geom() biophys() geom_nseg() } create axon[1] proc topol() { local i basic_shape() } proc basic_shape() { axon[0] {pt3dclear() pt3dadd(0, 0, 0, 5) pt3dadd(0, 0, 1400, 5)} } objref all proc subsets() { local i objref all all = new SectionList() axon[0] all.append() } proc geom() { } proc geom_nseg() { forall {nseg = 2} } proc biophys() { } celldef() Ra = 100. cm = 1. Rm = 30000 forall { insert pas } """) dt = 2**-4 cell_params = { # various cell parameters, 'morphology': h.all, 'delete_sections': False, 'v_init': -70., # initial crossmembrane potential 'passive': False, # switch on passive mechs 'nsegs_method': None, 'lambda_f': 1000., 'dt': dt, # [ms] dt's should be in powers of 2 for both, 'tstart': 0., # start time of simulation, recorders start at t=0 'tstop': 10., "pt3d": True, } cell = LFPy.Cell(**cell_params) # cell.set_pos(x=-cell.xstart[0]) return cell
synapse_params = { 'e' : 0., # reversal potential 'syntype' : 'Exp2Syn', # synapse type 'tau1' : 0.1, # synaptic time constant 'tau2' : 1., # synaptic time constant 'weight' : 0.001, # synaptic weight 'record_current' : True, # record synapse current } if "soma" in synapse_type: synapse_params["idx"] = cell.get_closest_idx(x=0, z=0) elif "tuft" in synapse_type: synapse_params["idx"] = cell.get_closest_idx(x=100, z=1400) synapse_params["weight"] = 0.2 synapses = [LFPy.Synapse(cell, **synapse_params)] synapses[0].set_spike_times(np.array([1., 5., 9.])) # synapses[0].set_spike_times(np.array([1.])) # Create a grid of measurement locations, in (mum) # grid_x, grid_z = np.mgrid[-550:551:25, -600:1501:25] # grid_x, grid_z = np.mgrid[-75:76:50, -75:76:50] grid_x, grid_z = np.mgrid[-75:76:50, -75:251:50] grid_y = np.zeros(grid_x.shape) # Define electrode parameters grid_elec_params = { 'sigma': 0.3, # extracellular conductivity 'x': grid_x.flatten(), # electrode requires 1d vector of positions 'y': grid_y.flatten(), 'z': grid_z.flatten()
def make_cell(self, ext_sim_dict, cell_z_pos, MEA): cell_parameters = { 'morphology': self.morphology_name, 'v_init': -65, 'passive': False, 'nsegs_method': 'lambda_f', 'lambda_f': 400, # Higher number means higher spatial resolution of the cell 'timeres_NEURON': 2**-3, # Should be a power of 2 'timeres_python': 2**-3, 'tstartms': 0, 'tstopms': 50, 'verbose': True, 'pt3d': True, } cell = LFPy.Cell(**cell_parameters) # Setting the passive parameters of the cell: for sec in cell.allseclist: sec.Ra = 100 # Ohm cm sec.cm = 1 # uF / cm2 sec.insert('pas') sec.g_pas = 1. / 30000 sec.e_pas = -65 # Specify the position and rotation of the cell cell.set_pos(zpos=cell_z_pos) #cell.set_rotation(x=np.pi,z=0*np.pi) syn_idx = cell.get_closest_idx(x=self.syn_pos[0], y=self.syn_pos[1], z=self.syn_pos[2], section='dend') synapse_parameters = { 'idx': syn_idx, 'e': 0., # Change to -90 for inhibitory input, and 0 for excitatory 'syntype': 'Exp2Syn', 'tau1': 1., 'tau2': 1., 'weight': self.syn_weight, 'record_current': True, } synapse = LFPy.Synapse(cell, **synapse_parameters) synapse.set_spike_times(self.input_spike_train) # If no parameters are changed, we can just load results from file if self.simulate_cell: print "Simulating cell" cell.simulate(rec_imem=True, rec_vmem=True, rec_isyn=True) if not os.path.isdir(self.folder): os.mkdir(self.folder) print cell.imem.shape imemName = 'imem_z' + str(self.rel_dist) + '_' + str( self.index) + '.npy' np.save(join(self.folder, imemName), cell.imem) np.save(join(self.folder, 'tvec.npy'), cell.tvec) vmemName = 'vmem_z' + str(self.rel_dist) + '_' + str( self.index) + '.npy' np.save(join(self.folder, vmemName), cell.vmem) np.save(join(self.folder, 'syn_i.npy'), synapse.i) if os.path.isfile(join(self.folder, 'mapping_normal_saline.npy') ) and not self.calculate_mapping: mapping = np.load( join(self.folder, 'mapping_normal_saline.npy')) MEA.phi = np.dot(mapping, cell.imem) else: cell.imem = np.load(join(self.folder, 'imem.npy')) cell.vmem = np.load(join(self.folder, 'vmem.npy')) cell.tvec = np.load(join(self.folder, 'tvec.npy')) synapse.i = np.load(join(self.folder, 'syn_i.npy')) MEA.phi = np.load(join(self.folder, 'phi.npy')) if self.calculate_mapping: self.make_mapping(cell, MEA, ext_sim_dict, cell_z_pos) return cell, synapse
if not hasattr(neuron.h, biophysics): # Load biophysics neuron.h.load_file(1, "biophysics.hoc") if not hasattr(neuron.h, synapses): # load synapses neuron.h.load_file(1, posixpth(os.path.join('synapses', 'synapses.hoc'))) if not hasattr(neuron.h, templatename): # Load main cell template neuron.h.load_file(1, "template.hoc") for idx, morphologyfile in enumerate(glob(os.path.join('morphology', '*'))): # Instantiate the cell(s) using LFPy cell = LFPy.TemplateCell(morphology=morphologyfile, templatefile=posixpth(os.path.join(NRN, 'template.hoc')), templatename=templatename, templateargs=1 if add_synapses else 0, tstop=tstop, dt=dt, extracellular=True, nsegs_method=None) # set view as in most other examples cell.set_rotation(x=np.pi / 2) cell.set_pos(z=utils.set_z_layer(layer_name)) v_cell_ext = np.zeros((cell.totnsegs, n_tsteps)) v_cell_ext[:, :] = ExtPot.ext_field(cell.xmid, cell.ymid, cell.zmid).reshape(cell.totnsegs, 1) * pulse.reshape(1, n_tsteps) cell.insert_v_ext(v_cell_ext, t) # pointProcess = LFPy.StimIntElectrode(cell, **PointProcParams)
'cm': 1.0, # membrane capacitance 'Ra': 150., # axial resistance 'v_init': -65., # initial crossmembrane potential 'passive': True, # turn on NEURONs passive mechanism for all sections 'passive_parameters': { 'g_pas': 1. / 30000, 'e_pas': -65 }, 'nsegs_method': 'lambda_f', # spatial discretization method 'lambda_f': 100., # frequency where length constants are computed 'dt': 2.**-4, # simulation time step size 'tstart': 0., # start time of simulation, recorders start at t=0 'tstop': 100., # stop simulation at 100 ms. 'extracellular': True, } cell = LFPy.Cell(**cell_params) cell.set_rotation(x=4.99, y=-4.33, z=3.14) cortical_surface_height = np.max(cell.zend) + 20 # Parameters for the external field sigma = 0.3 amp = 100000. start_time = 20 source_xs = np.array([-70, -70, -10, -10, 10, 10, 70, 70]) source_ys = np.array([-70, 70, -10, 10, 10, -10, -70, 70]) source_zs = np.ones(len(source_xs)) * cortical_surface_height source_amps = np.array([-1, -1, 1, 1, 1, 1, -1, -1]) * amp ExtPot = ImposedPotentialField(source_amps, source_xs, source_ys, source_zs, sigma)
'n': 20, 'r': 10, 'N': N, } # Parameters for the cell.simulate() call, recording membrane- and syn.-currents simulationParameters = { 'rec_imem': True, # Record Membrane currents during simulation } ################################################################################ # Main simulation procedure ################################################################################ #Initialize cell instance, using the LFPy.Cell class cell = LFPy.Cell(**cellParameters) #Insert synapses using the function defined earlier insert_synapses(synapseParameters_AMPA, **insert_synapses_AMPA_args) insert_synapses(synapseParameters_NMDA, **insert_synapses_NMDA_args) insert_synapses(synapseParameters_GABA_A, **insert_synapses_GABA_A_args) #perform NEURON simulation, results saved as attributes in the cell instance cell.simulate(**simulationParameters) # Initialize electrode geometry, then calculate the LFP, using the # LFPy.RecExtElectrode class. Note that now cell is given as input to electrode # and created after the NEURON simulations are finished electrode = LFPy.RecExtElectrode(cell, **electrodeParameters) print('simulating LFPs....') electrode.calc_lfp()
def test_cell_set_pos_01(self): '''test LFPy.Cell.set_pos''' cell = LFPy.Cell(morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks.hoc')) cell.set_pos(10., 20., -30.) np.testing.assert_allclose(cell.somapos, [10., 20., -30.])
# containers for per-cell LFP and summed LFPs single_LFPs = [] summed_LFP = np.zeros(int(cell_parameters['tstop'] / cell_parameters['dt'] + 1)) # get state of random seed generator state = np.random.get_state() # iterate over cells in populations for cell_id in range(n_cells): if cell_id % SIZE == RANK: # get set seed per cell in order to synapse locations np.random.seed(global_seed + cell_id) # Create cell cell = LFPy.Cell(**cell_parameters) #Have to position and rotate the cells! cell.set_rotation(z=z_rotation[cell_id], **xy_rotations) cell.set_pos(x=x_cell_pos[cell_id]) for i_syn in range(n_synapses): syn_idx = cell.get_rand_idx_area_norm() synapse_parameters.update({'idx': syn_idx}) synapse = LFPy.Synapse(cell, **synapse_parameters) synapse.set_spike_times(pre_syn_sptimes[pre_syn_ids[cell_id % SIZE][i_syn]]) #run the cell simulation cell.simulate(rec_imem=True)
def test_cell_set_pos_05(self): '''test LFPy.Cell.set_pos''' cell = LFPy.Cell(morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks.hoc')) np.testing.assert_allclose(cell.somapos, [cell.xmid[0], cell.ymid[0], cell.zmid[0]])
def generate_eegs_nyh_n_4s(dip_loc): # set 4S properties # From Huang et al. (2013): 10.1088/1741-2560/10/6/066004 sigmas = [0.276, 1.65, 0.01, 0.465] radii = [89000., 90000., 95000., 100000.] print('sigmas:', sigmas) rad_tol = 1e-2 P_loc_4s_length = radii[0] - 1000 x_eeg, y_eeg, z_eeg = return_equidistal_xyz(224, r=radii[-1] - rad_tol) eeg_coords_4s = np.array([x_eeg, y_eeg, z_eeg]).T # get population dipole nyh = NYHeadModel() # hybrid current dipole moment nyh.load_hybrid_current_dipole() P = nyh.dipole_moment.T[875:951, :] # place dipole and find normal vector P_loc_nyh = nyh.dipole_pos_dict[dip_loc] nyh.set_dipole_pos(dipole_pos_0=P_loc_nyh) P_loc_idx = nyh.return_closest_idx(P_loc_nyh) norm_vec = nyh.cortex_normals[:, P_loc_idx] # find location on 4S # want to find position on brain, such that the location vector is # parallel to norm_vec from nyh. # length of position vector P_loc_4s = norm_vec * P_loc_4s_length P_rot = nyh.rotate_dipole_moment().T[875:951, :] # use this when comparing execution times elec_dists_4s = np.sqrt(np.sum((eeg_coords_4s - P_loc_4s)**2, axis=1)) elec_dists_4s *= 1e-3 # convert from um to mm min_dist_idx = np.argmin(elec_dists_4s) print("Minimum 4o distance {:2.02f} mm".format( elec_dists_4s[min_dist_idx])) time_idx = np.argmax(np.linalg.norm(P_rot, axis=1)) # if execution times: # time_idx = np.argmax(np.linalg.norm(P_rot[875:951,:], axis=1)) # potential in 4S with db four_sphere = LFPy.FourSphereVolumeConductor(radii, sigmas, eeg_coords_4s) start_4s = time.time() eeg_4s = four_sphere.calc_potential(P_rot, P_loc_4s) #[:,0] end_4s = time.time() time_4s = end_4s - start_4s # when comparing execution times: # eeg_4s = eeg_4s[:, 875:951] print('execution time 4S:', time_4s) # subtract DC-component dc_comp_4s = np.mean(eeg_4s[:, 0:25], axis=1) dc_comp_4s = np.expand_dims(dc_comp_4s, 1) eeg_4s -= dc_comp_4s eeg_4s *= 1e3 # from mV to uV # calculate EEGs with NYHeadModel start_nyh = time.time() nyh.calculate_eeg_signal(normal=True) end_nyh = time.time() time_nyh = end_nyh - start_nyh print('execution time NYH:', time_nyh) eeg_nyh = nyh.eeg[:, 875:951] # pV # subtract DC-component dc_comp_nyh = np.mean(eeg_nyh[:, 0:25], axis=1) dc_comp_nyh = np.expand_dims(dc_comp_nyh, 1) eeg_nyh -= dc_comp_nyh # from pV to uV eeg_nyh *= 1e-6 elec_dists_nyh = (np.sqrt( np.sum((np.array(nyh.dipole_pos)[:, None] - np.array(nyh.elecs[:3, :]))**2, axis=0))) eeg_coords_nyh = nyh.elecs # some info # max_eeg = np.max(np.abs(eeg_nyh[:, time_idx])) # max_eeg_idx = np.argmax(np.abs(eeg_nyh[:, time_idx])) # max_eeg_pos = eeg_coords_nyh[:3, max_eeg_idx] dist, closest_elec_idx = nyh.find_closest_electrode() print("Closest electrode to dipole: {:1.2f} mm".format(dist)) tvec = np.arange(P.shape[0]) + 875 np.savez( '../data/figure7_%s.npz' % dip_loc, radii=radii, p_rot=P_rot, p_loc_4s=P_loc_4s, p_loc_nyh=P_loc_nyh, eeg_coords_4s=eeg_coords_4s, eeg_coords_nyh=eeg_coords_nyh, elec_dists_4s=elec_dists_4s, elec_dists_nyh=elec_dists_nyh, eeg_4s=eeg_4s, eeg_nyh=eeg_nyh, time_idx=time_idx, tvec=tvec, )
def test_cell_get_rand_prob_area_norm_from_idx_00(self): '''test LFPy.Cell.get_rand_prob_area_norm()''' cell = LFPy.Cell(morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks.hoc')) p = cell.get_rand_prob_area_norm_from_idx(idx=np.array([0])) np.testing.assert_equal(p, np.array([1.]))
cell_parameters = { 'morphology' : 'morphologies/ball_and_2_sticks.hoc', # from Mainen & Sejnowski, J Comput Neurosci, 1996 'cm' : 1.0, # membrane capacitance 'Ra' : 150., # axial resistance #'v_init' : -65., # initial crossmembrane potential 'passive' : True, # turn on NEURONs passive mechanism for all sections 'passive_parameters' : {'g_pas' : 1./30000, 'e_pas' : -70}, 'nsegs_method' : 'lambda_f', # spatial discretization method 'lambda_f' : 100., # frequency where length constants are computed 'dt' : 2.**-5, # simulation time step size 'tstart' : -200., # start time of simulation, recorders start at t=0 'tstop' : 25., # stop simulation at 100 ms. } # Create cell cell = LFPy.Cell(**cell_parameters) # Align cell cell.set_rotation(x=4.99, y=-4.33, z=3.14) # Define synapse parameters synapse_parameters = { # 'idx' : 0, 'idx' :cell.get_closest_idx(x=0., y=0., z=0.), 'e' : 0., # reversal potential 'syntype' : 'Exp2Syn', # synapse type 'tau1' : 1., # synaptic time constant 'tau2' : 3., 'weight' : .000001*5000, # synaptic weight 'record_current' : True, # record synapse current }
def test_cell_get_idx_parent_children_00(self): cell = LFPy.Cell(morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks.hoc')) np.testing.assert_array_equal( cell.get_idx_parent_children(parent='soma[0]'), cell.get_idx(section=['soma[0]', 'dend[0]']))
def return_cell(cell_folder, model_type, cell_name, end_T, dt, start_T, verbose=False): """ Function to load cell models Parameters: ----------- cell_folder : string Path to folder where cell model is saved. model_type : string Cell model type (e.g. 'bbp' for Human Brain Project) cell_name : string Name of the cell end_T : float Simulation length [ms] dt: float Time step of simulation [ms] start_T: float Simulation start time (recording starts at 0 ms) Returns: -------- cell : object LFPy cell object """ import mpi4py.MPI import LFPy import neuron neuron.h.load_file("stdrun.hoc") neuron.h.load_file("import3d.hoc") cwd = os.getcwd() os.chdir(cell_folder) if verbose: print("Simulating ", cell_name) if model_type == 'bbp': neuron.load_mechanisms('../mods') f = open("template.hoc", 'r') templatename = get_templatename(f) f.close() f = open("biophysics.hoc", 'r') biophysics = get_templatename(f) f.close() f = open("morphology.hoc", 'r') morphology = get_templatename(f) f.close() # get synapses template name f = open(join("synapses", "synapses.hoc"), 'r') synapses = get_templatename(f) f.close() neuron.h.load_file('constants.hoc') if not hasattr(neuron.h, morphology): neuron.h.load_file(1, "morphology.hoc") if not hasattr(neuron.h, biophysics): neuron.h.load_file(1, "biophysics.hoc") if not hasattr(neuron.h, synapses): # load synapses neuron.h.load_file(1, join('synapses', 'synapses.hoc')) if not hasattr(neuron.h, templatename): neuron.h.load_file(1, "template.hoc") morphologyfile = os.listdir('morphology')[ 0] # glob('morphology\\*')[0] # Instantiate the cell(s) using LFPy cell = LFPy.TemplateCell(morphology=join('morphology', morphologyfile), templatefile=join('template.hoc'), templatename=templatename, templateargs=0, tstop=end_T, tstart=start_T, dt=dt, v_init=-70, pt3d=True, delete_sections=True, verbose=True) else: raise NotImplementedError('Cell model %s is not implemented' \ % model_type) os.chdir(cwd) return cell
def test_cell_get_idx_name_00(self): cell = LFPy.Cell(morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks.hoc')) np.testing.assert_array_equal( cell.get_idx_name(idx=np.array([0])), np.array([[0, 'soma[0]', 0.5]], dtype=object))
def test_Network_02(self): cellParameters = dict( morphology=os.path.join(LFPy.__path__[0], 'test', 'ball_and_sticks_w_lists.hoc'), templatefile=os.path.join(LFPy.__path__[0], 'test', 'ball_and_stick_template.hoc'), templatename='ball_and_stick_template', templateargs=None, passive=False, dt=2**-3, tstop=100, delete_sections=False, ) populationParameters = dict( CWD=None, CELLPATH=None, Cell=LFPy.NetworkCell, cell_args=cellParameters, pop_args=dict(radius=100, loc=0., scale=20.), rotation_args=dict(x=0, y=0), POP_SIZE=4, name='test', ) networkParameters = dict(dt=2**-3, tstart=0., tstop=100., v_init=-65., celsius=6.3, OUTPUTPATH='tmp_testNetworkPopulation') clampParams = { 'idx': 0, 'pptype': 'VClamp', 'amp[0]': -65, 'dur[0]': 10, 'amp[1]': 0, 'dur[1]': 1, 'amp[2]': -65, 'dur[2]': 1E8, } # set up network = LFPy.Network(**networkParameters) network.create_population(**populationParameters) connectivity = network.get_connectivity_rand(pre='test', post='test', connprob=1) # test connectivity self.assertTrue( np.all(connectivity == ( np.eye(populationParameters['POP_SIZE']) == 0))) # connect network.connect(pre='test', post='test', connectivity=connectivity, multapseargs=dict(loc=1, scale=1E-9)) # create synthetic AP in cell with gid == 0 for population in network.populations.values(): for cell in population.cells: if cell.gid == 0: vclamp = LFPy.StimIntElectrode(cell=cell, **clampParams) # simulate network.simulate() # test output for population in network.populations.values(): for cell in population.cells: self.assertFalse(np.all(cell.somav == network.v_init)) network.pc.gid_clear() os.system('rm -r tmp_testNetworkPopulation') neuron.h('forall delete_section()')
def constant_current_injection(self, amp, idx=0): self.point_process['idx'] = idx self.point_process['amp'] = amp self.point_process['dur'] = self.cell.tstop self.point_process['delay'] = 2 stimulus = LFPy.StimIntElectrode(self.cell, **self.point_process)
# boundaries of each layer. The products are normalized such that the sum of # each column is 1, i.e., the sum of layer specificities of a connection # between X and Y is 1. PSET.L_YXL_m_types = {} bins = np.r_[-PSET.layer_data['thickness'].cumsum()[::-1], 0] for i, (y, Y, pop_args_Y, rotation_args_Y) in enumerate( zip(PSET.populationParameters['m_type'], PSET.populationParameters['me_type'], PSET.populationParameters['pop_args'], PSET.populationParameters['rotation_args'])): # create a container for the layer specificities of connections data = np.zeros((PSET.layer_data.size, PSET.populationParameters.size)) # find and load the corresponding morphology files into LFPy m_Y = glob(os.path.join(PSET.CELLPATH, Y, 'morphology', '*.asc'))[0] cell_Y = LFPy.Cell(morphology=m_Y) cell_Y.set_rotation(**rotation_args_Y) cell_Y.set_pos(z=pop_args_Y['loc']) # sum the total length of axon in each layer bin layerbounds = np.r_[0, -PSET.layer_data['thickness'].cumsum()] len_Y_sum = np.zeros(PSET.layer_data.size) for k in range(PSET.layer_data.size): len_Y_sum[k] = cell_Y.length[cell_Y.get_idx( ['soma', 'dend', 'apic'], z_min=layerbounds[k + 1], z_max=layerbounds[k])].sum() for j, (X, pop_args_X, rotation_args_X) in enumerate( zip(PSET.populationParameters['me_type'], PSET.populationParameters['pop_args'], PSET.populationParameters['rotation_args'])):
'x': X.flatten(), # x,y,z-coordinates of contacts 'y': Y.flatten(), 'z': Z.flatten(), 'method': 'soma_as_point', #sphere source soma segment 'N': np.array([[0, 1, 0]] * X.size), #surface normals 'r': 2.5, # contact site radius 'n': 20, # datapoints for averaging } print('LFP grid generated') # delete old sections from NEURON namespace LFPy.cell.neuron.h("forall delete_section()") print('Deleted old sections') # create extracellular electrode object for LFPs on grid electrode = LFPy.RecExtElectrode(**electrodeParameters) print('Created extracellular electrode') # Initialize cell instance, using the LFPy.Cell class cell = LFPy.TemplateCell(**cellParameters) cell.set_rotation(x=4.729, y=-3.166) print('Cell initialized') # Override passive reversal potential, AP is generated for sec in cell.allseclist: for seg in sec: seg.e_pas = -59.5 print('Reversal potential set') # perform NEURON simulation, results saved as attributes in the cell instance cell.simulate(electrode=electrode) print('Electrode simulated')