def define_geometry(icc): icc.diam = 4.4 #7.136*2 icc.L = 65.92 icc.nseg = 1 icc.Ra = 50 #50 icc.cm = .025*(10**5)/h.area(0.5,sec=icc)
def area_in_list(self,seclist): area = 0 for sec in seclist: if h.ismembrane('chanrhod',sec = sec): for seg in sec: area += h.area(seg.x, sec=sec) # um2 return area
def set_seg_props(self): """Set segment properties which are invariant for all cell using this morphology""" seg_type = [] seg_area = [] seg_x = [] seg_dist = [] seg_length = [] h.distance(sec=self.hobj.soma[0]) # measure distance relative to the soma for sec in self.hobj.all: fullsecname = sec.name() sec_type = fullsecname.split(".")[1][:4] # get sec name type without the cell name sec_type_swc = self.sec_type_swc[sec_type] # convert to swc code for seg in sec: seg_area.append(h.area(seg.x)) seg_x.append(seg.x) seg_length.append(sec.L/sec.nseg) seg_type.append(sec_type_swc) # record section type in a list seg_dist.append(h.distance(seg.x)) # distance to the center of the segment self.seg_prop = {} self.seg_prop['type'] = np.array(seg_type) self.seg_prop['area'] = np.array(seg_area) self.seg_prop['x'] = np.array(seg_x) self.seg_prop['dist'] = np.array(seg_dist) self.seg_prop['length'] = np.array(seg_length) self.seg_prop['dist0'] = self.seg_prop['dist'] - self.seg_prop['length']/2 self.seg_prop['dist1'] = self.seg_prop['dist'] + self.seg_prop['length']/2
def compute_total_area(self): self.total_area = 0 for sec in h.allsec(): for seg in sec: self.total_area += h.area(seg.x, sec) if DEBUG: print('Total area: %.0f um^2.' % self.total_area)
def retrieve_coordinate(sec): sec.push() x, y, z, d = [],[],[],[] area = 0 tot_points = 0 connect_next = False for i in range(int(h.n3d())): present = False x_i = h.x3d(i) y_i = h.y3d(i) z_i = h.z3d(i) d_i = h.diam3d(i) a_i = h.area(0.5) if x_i in x: ind = len(x) - 1 - x[::-1].index(x_i) # Getting the index of last value if y_i == y[ind]: if z_i == z[ind]: present = True if not present: k =(x_i, y_i, z_i) x.append(x_i) y.append(y_i) z.append(z_i) d.append(d_i) area += np.sum(a_i) h.pop_section() #adding num 3d points per section n3dpoints[sec.name()] = [np.array(x),np.array(y),np.array(z),np.array(d)] return (np.array(x),np.array(y),np.array(z),np.array(d),area)
def retrieve_coordinate(sec): sec.push() x, y, z, d = [], [], [], [] area = 0 tot_points = 0 connect_next = False for i in range(int(h.n3d())): present = False x_i = h.x3d(i) y_i = h.y3d(i) z_i = h.z3d(i) d_i = h.diam3d(i) a_i = h.area(0.5) if x_i in x: ind = len(x) - 1 - x[::-1].index( x_i) # Getting the index of last value if y_i == y[ind]: if z_i == z[ind]: present = True if not present: k = (x_i, y_i, z_i) x.append(x_i) y.append(y_i) z.append(z_i) d.append(d_i) area += np.sum(a_i) h.pop_section() #adding num 3d points per section n3dpoints[sec.name()] = [ np.array(x), np.array(y), np.array(z), np.array(d) ] return (np.array(x), np.array(y), np.array(z), np.array(d), area)
def illuminated_area_in_list(self,seclist,Tx_threshold = 0.001): area = 0 for sec in seclist: if h.ismembrane('chanrhod',sec = sec): for seg in sec: if seg.Tx_chanrhod>Tx_threshold: area += h.area(seg.x, sec=sec) # um2 return area
def channels_in_list(self,seclist): channels = 0 for sec in seclist: if h.ismembrane('chanrhod',sec = sec): for seg in sec: rho = seg.channel_density_chanrhod/1e8 # 1/cm2 --> 1/um2 area = h.area(seg.x, sec=sec) # um2 n = rho * area channels += n return channels
def radiant_power(self,seclist): """ Find the radiant power integrated over all sections in seclist """ p = 0 for sec in seclist: for seg in sec: area = h.area(seg.x, sec=sec)*1e-8 # um2 --> cm2 #p += (area * self.amplitude * sec.Tx_chanrhod) # Add section's radiant power p += (area * self.amplitude * sec.Tx_chanrhod) return p
def get_icat(self): """ Determine the total amount of channelrhodopsin current in the cell """ icat = 0 for sec in h.allsec(): if h.ismembrane('chanrhod', sec=sec): for seg in sec: i = seg.icat_chanrhod # (mA/cm2) area = h.area(seg.x, sec=sec) / 1e8 # cm2 icat += area * i # mA return icat
def section_area(section): x_list = [] a = 0 for seg in section: x = seg.x x_list.append(x) for x in x_list: a += h.area(x, sec=section) return a
def define_geometry(icc): icc.diam = 4.4 #7.136*2 icc.L = 65.92 icc.nseg = 1 icc.Ra = 50 #50 area = 4 * 100 * 8 + 2 * 20 * 8 icc.cm = .025 * (10**5) / h.area(0.5, sec=icc) print('capacitance=', icc.cm)
def set_seg_props(self): """Set segment properties which are invariant for all cell using this morphology""" seg_type = [] seg_area = [] seg_x = [] seg_dist = [] seg_length = [] h.distance( sec=self.hobj.soma[0]) # measure distance relative to the soma for sec in self.hobj.all: fullsecname = sec.name() sec_type = fullsecname.split( ".")[1][:4] # get sec name type without the cell name sec_type_swc = self.sec_type_swc[sec_type] # convert to swc code for seg in sec: seg_area.append(h.area(seg.x)) seg_x.append(seg.x) seg_length.append(sec.L / sec.nseg) seg_type.append(sec_type_swc) # record section type in a list seg_dist.append(h.distance( seg.x)) # distance to the center of the segment ''' for sec in self.hobj.all: sec_name = sec.name() segs = [s for s in sec] seg_len = sec.L / sec.nseg print sec_name, sec.L, len(segs),':', for s in segs: seg_dist = h.distance(s.x) print '[{} - {} - {}]'.format(seg_dist-seg_len/2, seg_dist, seg_dist+seg_len/2), # print h.distance(s.x), #print s.x, print '({})'.format(sec.L/sec.nseg) #print ' ', #for s in segs: # print '[{} - {}]'.format() #print sec.name(), '-', len([s for s in sec]) ''' self.seg_prop = {} self.seg_prop['type'] = np.array(seg_type) self.seg_prop['area'] = np.array(seg_area) self.seg_prop['x'] = np.array(seg_x) self.seg_prop['dist'] = np.array(seg_dist) self.seg_prop['length'] = np.array(seg_length) self.seg_prop[ 'dist0'] = self.seg_prop['dist'] - self.seg_prop['length'] / 2 self.seg_prop[ 'dist1'] = self.seg_prop['dist'] + self.seg_prop['length'] / 2
def open_channels_in_list(self,seclist): open_channels = 0 for sec in seclist: if h.ismembrane('chanrhod', sec = sec): for seg in sec: rho = seg.channel_density_chanrhod/1e8 # 1/cm2 --> 1/um2 area = h.area(seg.x, sec=sec) # um2 try: f_open = seg.o2_chanrhod + seg.o1_chanrhod # open fraction # 4 state model except: f_open = seg.o1_chanrhod # open fraction # 3 state model n = f_open * rho * area open_channels += n return open_channels
def define_biophysics(self): #Function: define_biophysics #Input: self #Process: set parameters #Output: neurons with biophysics self.totalarea = 0 for sec in self.all: # 'all' exists in parent object. sec.Ra = 1e-5 # Axial resistance in Ohm * cm sec.cm = 1 # Membrane capacitance in micro Farads / cm^2 for seg in sec: self.totalarea += h.area(seg.x) # Dendrite passive for d in self.dendlist: d.insert('leak')
def _do_memb_scales(self): if not self._scale_by_area: areas = numpy.ones(len(areas)) else: areas = numpy.array( sum([ list(self._regions[0]._geometry.volumes1d(sec) for sec in self._regions[0].secs) ], [])) neuron_areas = [] for sec in self._regions[0].secs: neuron_areas += [ h.area((i + 0.5) / sec.nseg, sec=sec) for i in xrange(sec.nseg) ] neuron_areas = numpy.array(neuron_areas) area_ratios = areas / neuron_areas # still needs to be multiplied by the valence of each molecule self._memb_scales = -area_ratios * FARADAY / (10000 * molecules_per_mM_um3)
def define_biophysics(self): #Function: define_biophysics #Input: self #Process: set parameters #Output: neurons with biophysics self.totalarea = 0 for sec in self.all: # 'all' exists in parent object. sec.Ra = 1e-5 # Axial resistance in Ohm * cm sec.cm = self.Captot # Membrane capacitance in micro Farads / cm^2 for seg in sec: self.totalarea += h.area(seg.x) # Soma passive self.soma.insert('leak') self.soma.g_leak = self.condtot
factor2 = (np.float32(seg_count)+1.)/t_segs sp_name = str(sec.name()).rsplit('.')[-1]+"_"+str(seg_count) try: location_dict[sp_name] = [(x[-1]*factor1)+(x[0]*(1-factor1)), (y[-1]*factor1)+(y[0]*(1-factor1)), (z[-1]*factor1)+(z[0]*(1-factor1)), (d[-1]*factor1)+(d[0]*(1-factor1)), (x[-1]*factor2)+(x[0]*(1-factor2)), (y[-1]*factor2)+(y[0]*(1-factor2)), (z[-1]*factor2)+(z[0]*(1-factor2)), (d[-1]*factor2)+(d[0]*(1-factor2)), ] except IndexError: #no location specified location_dict[sp_name] = location_dict['soma[0]_0']#[0,0,0,0,0,0,0,0] i_dict[sp_name] = [ina, ik, ica, i_cap, i_pas, ih] sec_dict[sp_name] = sec area_dict[sp_name] = h.area( ((2.*seg_count)+1)/(2.*sec.nseg) ) #Default simulation parameters thresh = -20 spikezaehler = h.NetCon(h.L5PCtemplate[0].soma[0](0.5)._ref_v, None, thresh, 0, 0) spikes = h.Vector() spikezaehler.record(spikes) t_vec = h.Vector() t_vec.record(h._ref_t) #RUN SIMULATION h.init() h.run() #CALCULATIONS BEFORE PLOTTING t_vec = np.array(t_vec)
def main(config, template_path, output_path, forest_path, populations, distance_bin_size, io_size, chunk_size, value_chunk_size, cache_size, verbose): """ :param config: :param template_path: :param forest_path: :param populations: :param io_size: :param chunk_size: :param value_chunk_size: :param cache_size: """ utils.config_logging(verbose) logger = utils.get_script_logger(script_name) comm = MPI.COMM_WORLD rank = comm.rank env = Env(comm=MPI.COMM_WORLD, config_file=config, template_paths=template_path) configure_hoc_env(env) if io_size == -1: io_size = comm.size if rank == 0: logger.info('%i ranks have been allocated' % comm.size) if output_path is None: output_path = forest_path if rank == 0: if not os.path.isfile(output_path): input_file = h5py.File(forest_path, 'r') output_file = h5py.File(output_path, 'w') input_file.copy('/H5Types', output_file) input_file.close() output_file.close() comm.barrier() layers = env.layers layer_idx_dict = { layers[layer_name]: layer_name for layer_name in ['GCL', 'IML', 'MML', 'OML', 'Hilus'] } (pop_ranges, _) = read_population_ranges(forest_path, comm=comm) start_time = time.time() for population in populations: logger.info('Rank %i population: %s' % (rank, population)) count = 0 (population_start, _) = pop_ranges[population] template_class = load_cell_template(env, population, bcast_template=True) measures_dict = {} for gid, morph_dict in NeuroH5TreeGen(forest_path, population, io_size=io_size, comm=comm, topology=True): if gid is not None: logger.info('Rank %i gid: %i' % (rank, gid)) cell = cells.make_neurotree_cell(template_class, neurotree_dict=morph_dict, gid=gid) secnodes_dict = morph_dict['section_topology']['nodes'] apicalidx = set(cell.apicalidx) basalidx = set(cell.basalidx) dendrite_area_dict = {k: 0.0 for k in layer_idx_dict} dendrite_length_dict = {k: 0.0 for k in layer_idx_dict} dendrite_distances = [] dendrite_diams = [] for (i, sec) in enumerate(cell.sections): if (i in apicalidx) or (i in basalidx): secnodes = secnodes_dict[i] for seg in sec.allseg(): L = seg.sec.L nseg = seg.sec.nseg seg_l = L / nseg seg_area = h.area(seg.x) seg_diam = seg.diam seg_distance = get_distance_to_node( cell, list(cell.soma)[0], seg.sec, seg.x) dendrite_diams.append(seg_diam) dendrite_distances.append(seg_distance) layer = synapses.get_node_attribute( 'layer', morph_dict, seg.sec, secnodes, seg.x) dendrite_length_dict[layer] += seg_l dendrite_area_dict[layer] += seg_area dendrite_distance_array = np.asarray(dendrite_distances) dendrite_diam_array = np.asarray(dendrite_diams) dendrite_distance_bin_range = int( ((np.max(dendrite_distance_array)) - np.min(dendrite_distance_array)) / distance_bin_size) + 1 dendrite_distance_counts, dendrite_distance_edges = np.histogram( dendrite_distance_array, bins=dendrite_distance_bin_range, density=False) dendrite_diam_sums, _ = np.histogram( dendrite_distance_array, weights=dendrite_diam_array, bins=dendrite_distance_bin_range, density=False) dendrite_mean_diam_hist = np.zeros_like(dendrite_diam_sums) np.divide(dendrite_diam_sums, dendrite_distance_counts, where=dendrite_distance_counts > 0, out=dendrite_mean_diam_hist) dendrite_area_per_layer = np.asarray([ dendrite_area_dict[k] for k in sorted(dendrite_area_dict.keys()) ], dtype=np.float32) dendrite_length_per_layer = np.asarray([ dendrite_length_dict[k] for k in sorted(dendrite_length_dict.keys()) ], dtype=np.float32) measures_dict[gid] = { 'dendrite_distance_hist_edges': np.asarray(dendrite_distance_edges, dtype=np.float32), 'dendrite_distance_counts': np.asarray(dendrite_distance_counts, dtype=np.int32), 'dendrite_mean_diam_hist': np.asarray(dendrite_mean_diam_hist, dtype=np.float32), 'dendrite_area_per_layer': dendrite_area_per_layer, 'dendrite_length_per_layer': dendrite_length_per_layer } del cell count += 1 else: logger.info('Rank %i gid is None' % rank) append_cell_attributes(output_path, population, measures_dict, namespace='Tree Measurements', comm=comm, io_size=io_size, chunk_size=chunk_size, value_chunk_size=value_chunk_size, cache_size=cache_size) MPI.Finalize()
def Constructing_the_ball_and_tree(params, cables, spiking_mech=False, nmda_on=False, Ca_spikes_on=False, HH_on=False): # list of excitatory stuff exc_synapses, exc_netcons, exc_spike_trains, exc_Ks = [], [], [], [] # list of inhibitory stuff inh_synapses, inh_netcons, inh_spike_trains, inh_Ks = [], [], [], [] # area list area_lists = [] area_tot = 0 ## --- CREATING THE NEURON for level in range(len(cables)): # list of excitatory stuff per level exc_synapse, exc_netcon, exc_spike_train, exc_K = [], [], [], [] # list of inhibitory stuff per level inh_synapse, inh_netcon, inh_spike_train, inh_K = [], [], [], [] area_list = [] for comp in range(max(1,2**(level-1))): nrn('create cable_'+str(int(level))+'_'+\ str(int(comp))) exec('section = nrn.cable_'+str(level)+'_'+str(comp)) ## --- geometric properties section.L = cables[level]['L']*1e6 section.diam = cables[level]['D']*1e6 section.nseg = cables[level]['NSEG'] ## --- passive properties section.Ra = params['Ra']*1e2 section.cm = params['cm']*1e2 section.insert('pas') section.g_pas = params['g_pas']*1e-4 section.e_pas = params['El']*1e3 if comp==0 and HH_on: section.insert('hh3Larkum2009') if (comp==1 or comp==2) and Ca_spikes_on: section.insert('scaLarkum2009') section.gbar_scaLarkum2009=10 # section.insert('kdrLarkum2009') # section.insert('kcaLarkum2009') # section.gbar_kcaLarkum2009=30 section.insert('cad2Larkum2009') section.insert('it2Larkum2009') # section.gcabar_it2Larkum2009=0.000 # section.insert('hh3Larkum2009') # section.gkbar_hh3Larkum2009=0 # section.gkbar2_hh3Larkum2009=0.0001 # section.gnabar_hh3Larkum2009=0.01 # section.insert('kapLarkum2009') # section.gkabar_kapLarkum2009=0.003 # section.insert('kmLarkum2009') # section.gbar_kmLarkum2009=0 # section.gbar_kdrLarkum2009=0 if level>=1: # if not soma # in NEURON : connect daughter, mother branch nrn('connect cable_'+str(int(level))+'_'+\ str(int(comp))+'(0), '+\ 'cable_'+str(int(level-1))+\ '_'+str(int(comp/2.))+'(1)') ## --- SPREADING THE SYNAPSES (bis) for seg in section: tree_fraction = np.max([0,float(seg.x)/(len(cables)-1)+float(level-1)/(len(cables)-1)]) if tree_fraction>params['fraction_for_L_prox']: # print 'strengthen synapse !' Ftau = 1. # removed params ! Fq = params['factor_for_distal_synapses_weight'] else: Ftau = 1. Fq = 1. # in each segment, we insert an excitatory synapse if nmda_on: syn = nrn.my_glutamate(seg.x, sec=section) syn.tau_ampa, syn.e = Ftau*params['Te']*1e3, params['Ee']*1e3 syn.gmax = 1e9*params['Qe'] # nS in my_glutamate.mod else: syn = nrn.ExpSyn(seg.x, sec=section) syn.tau, syn.e = Ftau*params['Te']*1e3, params['Ee']*1e3 exc_synapse.append(syn) netcon = nrn.NetCon(nrn.nil, syn) netcon.weight[0] = Fq*params['Qe']*1e6 exc_netcon.append(netcon) exc_K.append(cables[level]['Ke_per_seg']) exc_spike_train.append([]) syn = nrn.ExpSyn(seg.x, sec=section) syn.tau, syn.e = Ftau*params['Ti']*1e3, params['Ei']*1e3 inh_synapse.append(syn) inh_K.append(cables[level]['Ki_per_seg']) inh_spike_train.append([]) netcon = nrn.NetCon(nrn.nil, syn) netcon.weight[0] = Fq*params['Qi']*1e6 inh_netcon.append(netcon) # then just the area to check area_tot+=nrn.area(seg.x, sec=section) area_list.append(nrn.area(seg.x, sec=section)) exc_synapses.append(exc_synapse) exc_netcons.append(exc_netcon) exc_Ks.append(exc_K) exc_spike_trains.append(exc_spike_train) inh_synapses.append(inh_synapse) inh_netcons.append(inh_netcon) inh_Ks.append(inh_K) inh_spike_trains.append(inh_spike_train) area_lists.append(area_list) # ## --- spiking properties if spiking_mech: # only at soma if we want it ! nrn('cable_0_0 insert hh') # + spikes recording ! counter = nrn.APCount(0.5, sec=nrn.cable_0_0) spkout = nrn.Vector() counter.thresh = -30 counter.record(spkout) else: spkout = np.zeros(0) print("=======================================") print(" --- checking if the neuron is created ") nrn.topology() print(("with the total surface : ", area_tot)) print("=======================================") return exc_synapses, exc_netcons, exc_Ks, exc_spike_trains,\ inh_synapses, inh_netcons, inh_Ks, inh_spike_trains, area_lists, spkout
def _do_memb_scales(self, cur_map): if not self._scale_by_area: areas = numpy.ones(len(areas)) else: # TODO: simplify this expression areas = numpy.array( itertools.chain.from_iterable([ list(self._regions[0]._geometry.volumes1d(sec) for sec in self._regions[0].secs) ])) neuron_areas = [] for sec in self._regions[0].secs: neuron_areas += [ h.area((i + 0.5) / sec.nseg, sec=sec) for i in range(sec.nseg) ] neuron_areas = numpy.array(neuron_areas) # area_ratios is usually a vector of 1s area_ratios = areas / neuron_areas # still needs to be multiplied by the valence of each molecule self._memb_scales = -area_ratios * FARADAY / (10000 * molecules_per_mM_um3) #print area_ratios #print self._memb_scales #import sys #sys.exit() # since self._memb_scales is only used to compute currents as seen by the rest of NEURON, # we only use NEURON's areas #self._memb_scales = volume * molecules_per_mM_um3 / areas if self._membrane_flux: # TODO: don't assume/require always inside/outside on one side... # if no nrn_region specified, then (make so that) no contribution # to membrane flux source_regions = [s()._region()._nrn_region for s in self._sources] dest_regions = [d()._region()._nrn_region for d in self._dests] if 'i' in source_regions and 'o' not in source_regions and 'i' not in dest_regions: inside = -1 #'source' elif 'o' in source_regions and 'i' not in source_regions and 'o' not in dest_regions: inside = 1 # 'dest' elif 'i' in dest_regions and 'o' not in dest_regions and 'i' not in source_regions: inside = 1 # 'dest' elif 'o' in dest_regions and 'i' not in dest_regions and 'o' not in source_regions: inside = -1 # 'source' else: raise RxDException( 'unable to identify which side of reaction is inside (hope to remove the need for this' ) # dereference the species to get the true species if it's actually a SpeciesOnRegion sources = [s()._species() for s in self._sources] dests = [d()._species() for d in self._dests] if self._membrane_flux: if any(s in dests for s in sources) or any(d in sources for d in dests): # TODO: remove this limitation raise RxDException( 'current fluxes do not yet support same species on both sides of reaction' ) # TODO: make so don't need multiplicity (just do in one pass) # TODO: this needs changed when I switch to allowing multiple sides on the left/right (e.g. simplified Na/K exchanger) self._cur_charges = tuple( [-inside * s.charge for s in sources if s.name is not None] + [inside * s.charge for s in dests if s.name is not None]) self._net_charges = sum(self._cur_charges) self._cur_ptrs = [] self._cur_mapped = [] for sec in self._regions[0].secs: for i in range(sec.nseg): local_ptrs = [] local_mapped = [] for sp in itertools.chain(self._sources, self._dests): spname = sp()._species().name if spname is not None: name = '_ref_i%s' % (spname) seg = sec((i + 0.5) / sec.nseg) local_ptrs.append(seg.__getattribute__(name)) uberlocal_map = [None, None] if spname + 'i' in cur_map: uberlocal_map[0] = cur_map[spname + 'i'][seg] if spname + 'o' in cur_map: uberlocal_map[1] = cur_map[spname + 'o'][seg] local_mapped.append(uberlocal_map) self._cur_ptrs.append(tuple(local_ptrs)) self._cur_mapped.append(tuple(local_mapped))
def calc_area(self): self.total_area = 0 self.n = 0 for sect in self.all_sec: self.total_area += h.area(0.5, sec=sect) self.n += 1
def insert_mechanisms(icc): icc.insert('pas') icc.g_pas = .01 icc(0.5).g_pas = 0 icc.insert('Na') icc.nai = nai_ icc.nao = nao_ icc.ena = ena_ icc.G_Na_Na = 0 #20 icc.tau_f_Na_Na = tau_f_Na icc.tau_d_Na_Na = tau_d_Na icc.insert('nscc') icc.G_NSCC_nscc = 0 #12.15 icc.tau_NSCC_nscc = tau_NSCC icc.insert('ERG') icc.G_ERG_ERG = 0 #2.5 icc.tau_ERG_ERG = tau_ERG icc.ki = ki_ #23 icc.ko = ko_ #23 icc.ek = ek_ #23 icc.insert('bk') icc.G_bk_bk = 0 #23+T_correction_BK icc.insert('Kb') icc.G_Kb_Kb = 0 #.15 icc.insert('kv11') icc.G_Kv11_kv11 = 0 #6.3 icc.tau_d_kv11_kv11 = tau_d_kv11 icc.tau_f_kv11_kv11 = tau_f_kv11 icc.insert('vddr') icc.G_Ca_VDDR_vddr = 0 #3 icc.cao = 2.5 icc.tau_d_VDDR_vddr = tau_d_VDDR icc.tau_f_VDDR_vddr = tau_f_VDDR icc.insert('ltype') icc.G_Ca_Ltype_ltype = 0 #2 icc.tau_f_Ltype_ltype = tau_f_Ltype icc.tau_d_Ltype_ltype = tau_d_Ltype icc.tau_f_Ca_Ltype_ltype = tau_f_Ca_Ltype icc.insert('pmca') icc.J_max_PMCA_pmca = 0 #0.088464 time_corr = 10**(-3) icc.insert('concyto') J_max_leak = 0.01 * time_corr icc.J_max_leak_concyto = 0 #0.01(mM/s) icc.Vol_concyto = pi * ((icc.diam / 2)**2) * icc.L icc.insert('conpu') icc.J_max_leak_conpu = 0 #0.01(mM/s) icc.Jmax_serca_conpu = 0 # 1.8333 icc.J_ERleak_conpu = 0 # 1.666667 icc.Jmax_IP3_conpu = 0 #50000 (1/s) icc.Jmax_NaCa_conpu = 0 #0.05(mM/s) icc.Jmax_uni_conpu = 0 #5000 mM/s icc.insert('ano1') icc.g_Ano1_ano1 = 0 #20 icc.cli = cli_ icc.clo = clo_ icc.ecl = ecl_ icc.insert('cacl') icc.G_Cacl_cacl = 0 #10.1 icc.tau_act_Cacl_cacl = tau_act_Cacl active_sites = [0.5] a = 1 / (10 * h.area(0.5)) for i in active_sites: icc( i ).G_Na_Na = a * 20 #.0022 #this is the tuned value #20 - total conductance icc(i).G_NSCC_nscc = a * 0 #12.15 icc(i).G_ERG_ERG = a * 2.5 #2.5 icc(i).G_bk_bk = a * (23 + T_correction_BK) #23+T_correction_BK icc(i).G_Kb_Kb = a * 0.15 #.15 icc(i).G_Kv11_kv11 = a * 6.3 #6.3 icc(i).G_Ca_VDDR_vddr = a * 3 #3 icc(i).G_Ca_Ltype_ltype = a * 2 #2 icc(i).J_max_PMCA_pmca = 0.088464 * time_corr #0.088464 icc(i).J_max_leak_concyto = J_max_leak #0.01(mM/s) icc(i).J_max_leak_conpu = J_max_leak #0.01(mM/s) icc(i).Jmax_serca_conpu = 1.8333 * time_corr # 1.8333 icc(i).J_ERleak_conpu = 1.666667 * time_corr # 1.666667 icc(i).Jmax_IP3_conpu = 50000 * time_corr #50000 (1/s) icc(i).Jmax_NaCa_conpu = 0.05 * time_corr #0.05(mM/s) icc(i).Jmax_uni_conpu = 5000 * time_corr #5000 mM/s icc(i).g_Ano1_ano1 = a * 20 #20 icc(i).G_Cacl_cacl = a * 10.1 #10.1
# plt.show() #print(icc.tau_f_Na_Na, tau_f_Na_Na) # plt.plot(t,ina, label = 'i_na') # plt.plot(t,ik_ERG, label = 'i_erg') # plt.plot(t,ik_Kb, label = 'i_kb') # plt.plot(t,ik_bk, label = 'ik_bk') # plt.plot(t,ik_kv11, label = 'i_kv11') # plt.plot(t,ica_vddr, label = 'i_vddr') # plt.plot(t,cai) # plt.plot(t,capui) # plt.plot(t,caeri) # plt.plot(ecl) # plt.plot(eca) # plt.plot(t,ik_bk, label = 'i_na') # plt.plot(t,ica_ltype, label = 'i_ltype') # plt.plot(t,icl_cacl, label = 'i_cacl') # plt.plot(t,icl_ano1, label = 'i_ano1') # plt.plot(t,i_nscc, label = 'i_nscc') # plt.plot(t,ica_pmca, label = 'i_pmca') plt.show() print(h.area(0.5))
""" Topology - connectivity between sections """ dend.connect(soma(1)) """ Geometry - 3D location of the sections """ # Surface area of cylinder is 2*pi*r*h (sealed ends are implicit). # Here we make a square cylinder in that the diameter # is equal to the height, so diam = h. ==> Area = 4*pi*r^2 # We want a soma of 500 microns squared: # r^2 = 500/(4*pi) ==> r = 6.2078, diam = 12.6157 soma.L = soma.diam = 12.6157 dend.L = 200 # microns dend.diam = 1 # microns print "Surface area of soma=", h.area(0.5, sec=soma) shape_window = h.PlotShape() shape_window.exec_menu('Show Diam') """ Biophysics - ionic channels and membrane properties of the sections """ for sec in h.allsec(): sec.Ra = 100 sec.cm = 1 # Active HH current in soma soma.insert('hh') soma.gnabar_hh = 0.12 soma.gkbar_hh = 0.036 soma.gl_hh = 0.0003
def setup_lfp_coeffs(self): ex, ey, ez = self.epoint for pop_name in self.celltypes: lfp_ids = self.lfp_ids[pop_name] lfp_types = self.lfp_types[pop_name] lfp_coeffs = self.lfp_coeffs[pop_name] for i in range(0, int(lfp_ids.size())): ## Iterates over all cells chosen for the LFP computation gid = lfp_ids.x[i] cell = self.pc.gid2cell(gid) ## Iterates over each compartment of the cell for sec in list(cell.all): if h.ismembrane('extracellular', sec=sec): nn = sec.n3d() xx = h.Vector(nn) yy = h.Vector(nn) zz = h.Vector(nn) ll = h.Vector(nn) for ii in range(0, nn): xx.x[ii] = sec.x3d(ii) yy.x[ii] = sec.y3d(ii) zz.x[ii] = sec.z3d(ii) ll.x[ii] = sec.arc3d(ii) xint = h.Vector(sec.nseg + 2) yint = h.Vector(sec.nseg + 2) zint = h.Vector(sec.nseg + 2) interpxyz(nn, sec.nseg, xx, yy, zz, ll, xint, yint, zint) j = 0 sx0 = xint.x[0] sy0 = yint.x[0] sz0 = zint.x[0] for seg in sec: sx = xint.x[j] sy = yint.x[j] sz = zint.x[j] ## l = L/nseg is compartment length ## rd is the perpendicular distance from the electrode to a line through the compartment ## ld is longitudinal distance along this line from the electrode to one end of the compartment ## sd = l - ld is longitudinal distance to the other end of the compartment l = float(sec.L) / sec.nseg rd = math.sqrt((ex - sx) * (ex - sx) + (ey - sy) * (ey - sy) + (ez - sz) * (ez - sz)) ld = math.sqrt((sx - sx0) * (sx - sx0) + (sy - sy0) * (sy - sy0) + (sz - sz0) * (sz - sz0)) sd = l - ld k = 0.0001 * h.area(seg.x) * (self.rho / (4.0 * math.pi * l)) * abs(math.log( ((math.sqrt(ld * ld + rd * rd) - ld) / (math.sqrt(sd * sd + rd * rd) - sd)))) if math.isnan(k): k = 0. ## Distal cell if (lfp_types.x[i] == 2): k = (1.0 / self.fdst) * k ##printf ("host %d: npole_lfp: gid = %d i = %d j = %d r = %g h = %g k = %g\n", pc.id, gid, i, j, r, h, k) lfp_coeffs.o(i).x[j] = k j = j + 1
import sys sys.path.append('../../') from neuron import h from neuron import gui from templates.mli.stellate import Stellate from templates.synapse.synapse import Synapse import numpy as np import random as rnd stls = [] stls.append(Stellate(np.array([0., 0., 0.]), model_type='C')) stls[0].soma.push() print h.area(.5) * 1e-8, ' cm2' vc = h.VClamp(.5, sec=stls[0].soma) vc.amp[0] = -80 # mV vc.dur[0] = 100 vc.amp[1] = -90 # mV vc.dur[1] = 300 vc.amp[2] = -80 # mV vc.dur[2] = 100 vclampi = h.Vector() vclampi.record(vc._ref_i) npf = 1
cells.append(cell) #cells[a].soma.gcaN_clarke = cells[a].soma.gcaN_clarke + step #cells[a].soma.gcaL_clarke = cells[a].soma.gcaL_clarke + step #cells[a].soma.gcak_clarke = cells[a].soma.gcak_clarke + step #cells[a].soma.gnapbar_clarke = cells[a].soma.gnapbar_clarke + step #cells[a].soma.tau_mc_clarke = cells[a].soma.tau_mc_clarke + step #cells[a].soma.tau_hc_clarke = cells[a].soma.tau_hc_clarke + step #cells[a].dap_nc_.weight[0] = cells[a].dap_nc_.weight[0] +step #cells[a].soma.gkrect_clarke = cells[a].soma.gkrect_clarke + step #cells[a].soma.tau_mp_bar_clarke = cells[a].soma.tau_mp_bar_clarke + step #cells[a].soma.tau_n_bar_clarke = cells[a].soma.tau_n_bar_clarke + step #cells[a].soma.gnabar_clarke = cells[a].soma.gnabar_clarke + step #shape_window = h.PlotShape() #shape_window.exec_menu('Show Diam') cellSurface = h.area(0.5, sec=cells[0].soma) ## Make a netstim stim = h.NetStim() # Make a new stimulator stim.interval = 150 stim.noise = 0 stim.number = 1 stim.start = 9200 ## Attach it to a synapse at syn_loc ncstim = h.NetCon(stim, cells[0].syn_I) ncstim.delay = 0 ncstim.weight[0] = 1.75e-3 # NetCon weight is a vector. #Stims and clamps #stim = h.IClamp(cells[0].dend(syn_loc)) #stim.delay = 200
location_dict[sp_name] = [ (x[-1] * factor1) + (x[0] * (1 - factor1)), (y[-1] * factor1) + (y[0] * (1 - factor1)), (z[-1] * factor1) + (z[0] * (1 - factor1)), (d[-1] * factor1) + (d[0] * (1 - factor1)), (x[-1] * factor2) + (x[0] * (1 - factor2)), (y[-1] * factor2) + (y[0] * (1 - factor2)), (z[-1] * factor2) + (z[0] * (1 - factor2)), (d[-1] * factor2) + (d[0] * (1 - factor2)), ] except IndexError: #no location specified location_dict[sp_name] = location_dict[ 'soma[0]_0'] #[0,0,0,0,0,0,0,0] i_dict[sp_name] = [ina, ik, ica, i_cap, i_pas, ih] sec_dict[sp_name] = sec area_dict[sp_name] = h.area(((2. * seg_count) + 1) / (2. * sec.nseg)) #Default simulation parameters thresh = -20 spikezaehler = h.NetCon(h.L5PCtemplate[0].soma[0](0.5)._ref_v, None, thresh, 0, 0) spikes = h.Vector() spikezaehler.record(spikes) t_vec = h.Vector() t_vec.record(h._ref_t) #RUN SIMULATION h.init() h.run() #CALCULATIONS BEFORE PLOTTING
soma = h.Section(name="soma") dir(soma) soma.insert("pas") soma.nseg = 3 h.psection(sec=soma) dend = h.Section(name="dend") dend.connect(soma, 1) dend.nseg = 10 print(h.topology()) soma.L = soma.diam = 12.6157 dend.L = 200 dend.diam = 1 h.area(0.1, sec=dend) pas = soma(0.5).pas pas.g = 0.002 print("pas: "******"\nALL SECTIONS:") for sec in h.allsec(): print(sec.name()) for seg in sec: print("\t" + str(seg.x)) for mech in seg: print("\t\t" + mech.name())
v_e.record(icc(0.6)._ref_v) v_e1.record(icc(0.7)._ref_v) v_e2.record(icc(.8)._ref_v) v_e3.record(icc(.9)._ref_v) v_e4.record(icc(1)._ref_v) vclamp = h.SEClamp(icc(0.5)) vclamp.dur1 = tstop vclamp.amp1 = -50.0 vclamp.rs = .00001 h.v_init = -80 run_and_record(icc, *variables) t = np.array(t.to_python()) ina = h.area(0.5) * 10 * np.array(ina.to_python()) ik = h.area(0.5) * 10 * np.array(ik.to_python()) ik_ERG = h.area(0.5) * 10 * np.array(ik_ERG.to_python()) ik_Kb = h.area(0.5) * 10 * np.array(ik_Kb.to_python()) ik_kv11 = h.area(0.5) * 10 * np.array(ik_kv11.to_python()) ica_vddr = h.area(0.5) * 10 * np.array(ica_vddr.to_python()) ik_bk = h.area(0.5) * 10 * np.array(ik_bk.to_python()) ica_ltype = h.area(0.5) * 10 * np.array(ica_ltype.to_python()) icl_cacl = h.area(0.5) * 10 * np.array(icl_cacl.to_python()) icl_ano1 = h.area(0.5) * 10 * np.array(icl_ano1.to_python()) cai_vddr = np.array(cai.to_python()) capui = np.array(capui.to_python()) # ik = ik.to_python() # ina_new = [i * (h.area(0.5)*10) for i in ina]
N = 3 r = 50 # Radius of cell locations from origin (0,0,0) in microns for i in range(N): cell = ClarkeRelay() # When cells are created, the soma location is at (0,0,0) and # the dendrite extends along the X-axis. # First, at the origin, rotate about Z. cell.rotateZ(i*2*pi/N) # Then reposition x_loc = sin(i * 2 * pi / N) * r y_loc = cos(i * 2 * pi / N) * r cell.set_position(x_loc, y_loc, 0) cells.append(cell) cellSurface = h.area(0.5, sec = cells[0].soma) h.celsius = 37 #shape_window = h.PlotShape() #shape_window.exec_menu('Show Diam') #stim = h.NetStim() # Make a new stimulator # Attach it to a synapse in the middle of the dendrite # of the first cell in the network. (Named 'syn_' to avoid # being overwritten with the 'syn' var assigned later.) #syn_ = h.ExpSyn(cells[0].dend(0.5)) #syn_.tau = 10 #stim.number = 1 #stim.start = 9 #ncstim = h.NetCon(stim, syn_)
def _do_memb_scales(self, cur_map): """Set up self._memb_scales and cur_map.""" if not self._scale_by_area: areas = numpy.ones(len(areas)) else: volumes = numpy.concatenate([list(self._regions[0]._geometry.volumes1d(sec) for sec in self._regions[0].secs)]) neuron_areas = [] for sec in self._regions[0].secs: neuron_areas += [h.area((i + 0.5) / sec.nseg, sec=sec) for i in xrange(sec.nseg)] neuron_areas = numpy.array(neuron_areas) # area_ratios is usually a vector of 1s area_ratios = volumes / neuron_areas # still needs to be multiplied by the valence of each molecule self._memb_scales = -area_ratios * FARADAY / (10000 * molecules_per_mM_um3) #print area_ratios #print self._memb_scales #import sys #sys.exit() # since self._memb_scales is only used to compute currents as seen by the rest of NEURON, # we only use NEURON's areas #self._memb_scales = volume * molecules_per_mM_um3 / areas if self._membrane_flux: # TODO: don't assume/require always inside/outside on one side... # if no nrn_region specified, then (make so that) no contribution # to membrane flux source_regions = [s()._region()._nrn_region for s in self._sources] dest_regions = [d()._region()._nrn_region for d in self._dests] if 'i' in source_regions and 'o' not in source_regions and 'i' not in dest_regions: inside = -1 #'source' elif 'o' in source_regions and 'i' not in source_regions and 'o' not in dest_regions: inside = 1 # 'dest' elif 'i' in dest_regions and 'o' not in dest_regions and 'i' not in source_regions: inside = 1 # 'dest' elif 'o' in dest_regions and 'i' not in dest_regions and 'o' not in source_regions: inside = -1 # 'source' else: raise RxDException('unable to identify which side of reaction is inside (hope to remove the need for this') # dereference the species to get the true species if it's actually a SpeciesOnRegion sources = [s()._species() for s in self._sources] dests = [d()._species() for d in self._dests] if self._membrane_flux: if any(s in dests for s in sources) or any(d in sources for d in dests): # TODO: remove this limitation raise RxDException('current fluxes do not yet support same species on both sides of reaction') # TODO: make so don't need multiplicity (just do in one pass) # TODO: this needs changed when I switch to allowing multiple sides on the left/right (e.g. simplified Na/K exchanger) self._cur_charges = tuple([-inside * s.charge for s in sources if s.name is not None] + [inside * s.charge for s in dests if s.name is not None]) self._net_charges = sum(self._cur_charges) self._cur_ptrs = [] self._cur_mapped = [] for sec in self._regions[0].secs: for i in xrange(sec.nseg): local_ptrs = [] local_mapped = [] for sp in itertools.chain(self._sources, self._dests): spname = sp()._species().name if spname is not None: name = '_ref_i%s' % (spname) seg = sec((i + 0.5) / sec.nseg) local_ptrs.append(seg.__getattribute__(name)) uberlocal_map = [None, None] if spname + 'i' in cur_map: uberlocal_map[0] = cur_map[spname + 'i'][seg] # if spname + 'o' in cur_map: # uberlocal_map[1] = cur_map[spname + 'o'][seg] local_mapped.append(uberlocal_map) self._cur_ptrs.append(tuple(local_ptrs)) self._cur_mapped.append(tuple(local_mapped))
def compute_section_area(section): a = 0. for segment in section: a += h.area(segment.x, sec=section) return a
def test_direct_memory_transfer(): #h('''create soma''') cell = h.rinzelnrn() #h.psection() #dir(h) #h.soma.L=5.6419 #h.soma.diam=5.6419 #h.soma.insert("rinzelnrn") gc = 2.1 pp = 0.5 cell.soma.Ra = 1 cell.dend.Ra = 1 global_Ra = (1e-6 / (gc / pp * (h.area(0.5) * 1e-8) * 1e-3)) / (2 * h.ri(0.5)) cell.soma.Ra = global_Ra cell.soma.cm = 3 cell.dend.Ra = global_Ra cell.dend.cm = 3 # soma cell.soma.insert("pas") cell.soma.insert("kdr") cell.soma.insert("nafPR") cell.soma.gmax_nafPR = 30e-3 cell.soma.gmax_kdr = 15e-3 cell.soma.g_pas = 0.1e-3 cell.soma.e_pas = -60 # dend cell.dend.insert("pas") cell.dend.insert("rcadecay") cell.dend.insert("cal") cell.dend.insert("kcRT03") cell.dend.insert("rkq") cell.dend.g_pas = 0.1e-3 cell.dend.e_pas = -60 cell.dend.phi_rcadecay = 130 cell.dend.gmax_cal = 00010e-3 cell.dend.erev_cal = 80 cell.dend.gmax_kcRT03 = 00015e-3 cell.dend.gmax_rkq = 0000.8e-3 cell.dend.ek = -75 ic = h.IClamp(cell.soma(.5)) ic.delay = .5 ic.dur = 0.1 ic.amp = 0.3 #for testing external mod file #h.soma.insert("hh") h.cvode.use_fast_imem(1) h.cvode.cache_efficient(1) h.tstop = 50 h.celsius = 37.0 h.v_init = -60 v = h.Vector() v.record(cell.soma(.5)._ref_v, sec=cell.soma) i_mem = h.Vector() i_mem.record(cell.soma(.5)._ref_i_membrane_, sec=cell.soma) tv = h.Vector() tv.record(h._ref_t, sec=cell.soma) h.run() vstd = v.cl() tvstd = tv.cl() i_memstd = i_mem.cl() # Save current (after run) value to compare with transfer back from coreneuron #tran_std = [h.t, cell.soma(.5).v, cell.soma(.5).hh.m] from neuron import coreneuron coreneuron.enable = True pc = h.ParallelContext() pc.set_maxstep(10) h.stdinit() pc.psolve(h.tstop) #tran = [h.t, cell.soma(.5).v, cell.soma(.5).hh.m] assert (tv.eq(tvstd)) #assert(v.cl().sub(vstd).abs().max() < 1e-10) assert (i_mem.cl().sub(i_memstd).abs().max() < 1e-10) #assert(h.Vector(tran_std).sub(h.Vector(tran)).abs().max() < 1e-10) f = open('v.dat', 'w') for i in range(tv.size()): print('{} {}'.format(tv[i], v[i]), file=open("v.dat", "a")) h.quit()
def segment_area(input_segment): x = input_segment.x a = h.area(x, sec=input_segment.section) return a
def calc_area(self): self.total_area = 0 self.n = 0 for sect in self.all_sec: self.total_area += h.area(0.5,sec=sect) self.n+=1
def main(config, template_path, output_path, forest_path, populations, io_size, chunk_size, value_chunk_size, cache_size, verbose): """ :param config: :param template_path: :param forest_path: :param populations: :param io_size: :param chunk_size: :param value_chunk_size: :param cache_size: """ utils.config_logging(verbose) logger = utils.get_script_logger(script_name) comm = MPI.COMM_WORLD rank = comm.rank env = Env(comm=MPI.COMM_WORLD, config_file=config, template_paths=template_path) h('objref nil, pc, templatePaths') h.load_file("nrngui.hoc") h.load_file("./templates/Value.hoc") h.xopen("./lib.hoc") h.pc = h.ParallelContext() if io_size == -1: io_size = comm.size if rank == 0: logger.info('%i ranks have been allocated' % comm.size) h.templatePaths = h.List() for path in env.templatePaths: h.templatePaths.append(h.Value(1, path)) if output_path is None: output_path = forest_path if rank == 0: if not os.path.isfile(output_path): input_file = h5py.File(forest_path, 'r') output_file = h5py.File(output_path, 'w') input_file.copy('/H5Types', output_file) input_file.close() output_file.close() comm.barrier() (pop_ranges, _) = read_population_ranges(forest_path, comm=comm) start_time = time.time() for population in populations: logger.info('Rank %i population: %s' % (rank, population)) count = 0 (population_start, _) = pop_ranges[population] template_name = env.celltypes[population]['template'] h.find_template(h.pc, h.templatePaths, template_name) template_class = eval('h.%s' % template_name) measures_dict = {} for gid, morph_dict in NeuroH5TreeGen(forest_path, population, io_size=io_size, comm=comm, topology=True): if gid is not None: logger.info('Rank %i gid: %i' % (rank, gid)) cell = cells.make_neurotree_cell(template_class, neurotree_dict=morph_dict, gid=gid) secnodes_dict = morph_dict['section_topology']['nodes'] apicalidx = set(cell.apicalidx) basalidx = set(cell.basalidx) dendrite_area_dict = {k + 1: 0.0 for k in range(0, 4)} dendrite_length_dict = {k + 1: 0.0 for k in range(0, 4)} for (i, sec) in enumerate(cell.sections): if (i in apicalidx) or (i in basalidx): secnodes = secnodes_dict[i] prev_layer = None for seg in sec.allseg(): L = seg.sec.L nseg = seg.sec.nseg seg_l = old_div(L, nseg) seg_area = h.area(seg.x) layer = cells.get_node_attribute( 'layer', morph_dict, seg.sec, secnodes, seg.x) layer = layer if layer > 0 else ( prev_layer if prev_layer is not None else 1) prev_layer = layer dendrite_length_dict[layer] += seg_l dendrite_area_dict[layer] += seg_area measures_dict[gid] = { 'dendrite_area': np.asarray([ dendrite_area_dict[k] for k in sorted(dendrite_area_dict.keys()) ], dtype=np.float32), \ 'dendrite_length': np.asarray([ dendrite_length_dict[k] for k in sorted(dendrite_length_dict.keys()) ], dtype=np.float32) } del cell count += 1 else: logger.info('Rank %i gid is None' % rank) append_cell_attributes(output_path, population, measures_dict, namespace='Tree Measurements', comm=comm, io_size=io_size, chunk_size=chunk_size, value_chunk_size=value_chunk_size, cache_size=cache_size) MPI.Finalize()
def photons(self,sec): section_area = h.area(0.5,sec=sec) # um2 section_intensity = self.intensity(sec) # photons/ms cm2