def find_and_disconnect_axon(soma_ref): '''Searching for an axon, it can be a child of the soma or a parent of the soma.''' axon_section, axon_parent, soma_axon_x = [], False, None for sec in soma_ref.child: name = sec.hname().lower() if 'axon' in name or 'hill' in name: axon_section.append(sec) # disconnect axon soma_axon_x = sec.parentseg().x sec.push() h.disconnect() h.define_shape() if soma_ref.has_parent(): name = soma_ref.parent().sec.hname().lower() if 'axon' in name or 'hill' in name: axon_section.append(soma_ref.parent()) axon_parent = True soma_axon_x = None soma_ref.push() h.disconnect() else: raise Exception('Soma has a parent which is not an axon') if len(axon_section) > 1: raise Exception('Soma has a two axons') return axon_section, axon_parent, soma_axon_x
def fix_axon_allactive_granule(hobj): """Replace reconstructed axon with a stub Parameters ---------- hobj: instance of a Biophysical template NEURON's cell object """ # find the start and end diameter of the original axon, this is different from the perisomatic cell model # where diameter == 1. axon_diams = [hobj.axon[0].diam, hobj.axon[0].diam] h.distance(sec=hobj.soma[0]) # need this to set all distances relative to soma (not sure if from center?) for sec in hobj.all: section_name = sec.name().split(".")[1][:4] if section_name == 'axon': for seg in sec: if h.distance(seg.x) > 60: axon_diams[1] = sec.diam #if h.distance(0.5, sec) > 60: # axon_diams[1] = sec.diam for sec in hobj.axon: h.delete_section(sec=sec) h.execute('create axon[2]', hobj) for index, sec in enumerate(hobj.axon): sec.L = 30 sec.diam = axon_diams[index] # 1 hobj.axonal.append(sec=sec) hobj.all.append(sec=sec) # need to remove this comment hobj.axon[0].connect(hobj.soma[0], 1.0, 0) hobj.axon[1].connect(hobj.axon[0], 1.0, 0) h.define_shape()
def morph_per_root(root): morph = [] h.define_shape() for sec in secs_with_root(root): n3d = int(h.n3d(sec=sec)) x = [h.x3d(i, sec=sec) for i in xrange(n3d)] y = [h.y3d(i, sec=sec) for i in xrange(n3d)] z = [h.z3d(i, sec=sec) for i in xrange(n3d)] d = [h.diam3d(i, sec=sec) for i in xrange(n3d)] arc = [h.arc3d(i, sec=sec) for i in xrange(n3d)] length = sec.L half_dx = 0.5 / sec.nseg for seg in sec: morph.append(get_pts_between(x, y, z, d, arc, (seg.x - half_dx) * length, (seg.x + half_dx) * length)) # add end points for end_pt in [0, 1]: for sec in secs_with_root(root): n3d = int(h.n3d(sec=sec)) pt1 = [h.x3d(0, sec=sec), h.y3d(0, sec=sec), h.z3d(0, sec=sec), h.diam3d(0, sec=sec)] pt2 = [h.x3d(n3d - 1, sec=sec), h.y3d(n3d - 1, sec=sec), h.z3d(n3d - 1, sec=sec), h.diam3d(n3d - 1, sec=sec)] if h.section_orientation(sec=sec) == 0: morph_to_append = [pt1] if end_pt == 0 else [pt2] else: morph_to_append = [pt2] if end_pt == 0 else [pt1] round3(morph_to_append) morph.append(morph_to_append) return morph
def fix_axon(hobj): ''' Replace reconstructed axon with a stub Parameters ---------- hobj: instance of a Biophysical template NEURON's cell object ''' for sec in hobj.axon: h.delete_section(sec=sec) h.execute('create axon[2]', hobj) for sec in hobj.axon: sec.L = 30 sec.diam = 1 hobj.axonal.append(sec=sec) hobj.all.append(sec=sec) # need to remove this comment hobj.axon[0].connect(hobj.soma[0], 0.5, 0) hobj.axon[1].connect(hobj.axon[0], 1, 0) h.define_shape()
def morphology_to_dict(sections, outfile=None): section_map = {sec: i for i, sec in enumerate(sections)} result = [] h.define_shape() for sec in sections: my_parent = parent(sec) my_parent_loc = -1 if my_parent is None else parent_loc(sec, my_parent) my_parent = -1 if my_parent is None else section_map[my_parent] n3d = int(h.n3d(sec=sec)) result.append({ 'section_orientation': h.section_orientation(sec=sec), 'parent': my_parent, 'parent_loc': my_parent_loc, 'x': [h.x3d(i, sec=sec) for i in xrange(n3d)], 'y': [h.y3d(i, sec=sec) for i in xrange(n3d)], 'z': [h.z3d(i, sec=sec) for i in xrange(n3d)], 'diam': [h.diam3d(i, sec=sec) for i in xrange(n3d)], 'name': sec.hname() }) if outfile is not None: with open(outfile, 'w') as f: json.dump(result, f) return result
def initialize_neuron(swc_path, file_paths): h.load_file("stdgui.hoc") h.load_file("import3d.hoc") swc = h.Import3d_SWC_read() swc.input(swc_path) imprt = h.Import3d_GUI(swc, 0) h("objref this") imprt.instantiate(h.this) print file_paths for sec in h.allsec(): if sec.name().startswith("axon"): h.delete_section(sec=sec) axon = h.Section() axon.L = 60 axon.diam = 1 axon.connect(h.soma[0], 0.5, 0) h.define_shape() for sec in h.allsec(): sec.insert('pas') for seg in sec: seg.pas.e = 0 for file_path in file_paths: h.load_file(file_path.encode("ascii", "ignore"))
def fix_axon_allactive(hobj): """Replace reconstructed axon with a stub Parameters ---------- hobj: instance of a Biophysical template NEURON's cell object """ # find the start and end diameter of the original axon, this is different from the perisomatic cell model # where diameter == 1. axon_diams = [hobj.axon[0].diam, hobj.axon[0].diam] for sec in hobj.all: section_name = sec.name().split(".")[1][:4] if section_name == 'axon': axon_diams[1] = sec.diam for sec in hobj.axon: h.delete_section(sec=sec) h.execute('create axon[2]', hobj) for index, sec in enumerate(hobj.axon): sec.L = 30 print axon_diams[index] sec.diam = axon_diams[index] # 1 hobj.axonal.append(sec=sec) hobj.all.append(sec=sec) # need to remove this comment # original allen sdk: hobj.soma[0], 0.5, 0 hobj.axon[0].connect(hobj.soma[0], 1.0, 0) hobj.axon[1].connect(hobj.axon[0], 1, 0) h.define_shape()
def fix_axon_peri(hobj): """Replace reconstructed axon with a stub :param hobj: hoc object """ if hasattr(hobj, 'axon'): for i, sec in enumerate(hobj.axon): #h.delete_section(sec=sec) hobj.axon[i] = None for i,sec in enumerate(hobj.all): if 'axon' in sec.name(): hobj.all[i] = None hobj.all = [sec for sec in hobj.all if sec is not None] hobj.axon = None #h.execute('create axon[2]', hobj) hobj.axon = [h.Section(name='axon[0]'), h.Section(name='axon[1]')] hobj.axonal = [] for sec in hobj.axon: sec.L = 30 sec.diam = 1 hobj.axonal.append(sec) hobj.all.append(sec) # need to remove this comment hobj.axon[0].connect(hobj.soma[0], 0.5, 0) hobj.axon[1].connect(hobj.axon[0], 1, 0) h.define_shape()
def morphology_to_dict(sections, outfile=None): section_map = {sec: i for i, sec in enumerate(sections)} result = [] h.define_shape() for sec in sections: my_parent = parent(sec) my_parent_loc = -1 if my_parent is None else parent_loc(sec, my_parent) my_parent = -1 if my_parent is None else section_map[my_parent] n3d = int(h.n3d(sec=sec)) result.append({ 'section_orientation': h.section_orientation(sec=sec), 'parent': my_parent, 'parent_loc': my_parent_loc, 'x': [h.x3d(i, sec=sec) for i in xrange(n3d)], 'y': [h.y3d(i, sec=sec) for i in xrange(n3d)], 'z': [h.z3d(i, sec=sec) for i in xrange(n3d)], 'diam': [h.diam3d(i, sec=sec) for i in xrange(n3d)], 'name': sec.hname() }) if outfile is not None: with open(outfile, 'w') as f: json.dump(result, f) return result
def _fix_axon(self): """Removes and refixes axon""" axon_diams = [self._hobj.axon[0].diam, self._hobj.axon[0].diam] axon_indices = [] for i, sec in enumerate(self._hobj.all): section_name = sec.name().split(".")[1][:4] if section_name == 'axon': axon_diams[1] = sec.diam axon_indices.append(i) for sec in self._hobj.axon: h.delete_section(sec=sec) h.execute('create axon[2]', self._hobj) for index, sec in enumerate(self._hobj.axon): sec.L = 30 sec.diam = 1 self._hobj.axonal.append(sec=sec) self._hobj.all.append(sec=sec) # need to remove this comment self._hobj.axon[0].connect(self._hobj.soma[0], 1.0, 0) self._hobj.axon[1].connect(self._hobj.axon[0], 1.0, 0) h.define_shape()
def define_geometry(self): """Set the 3D geometry of the cell.""" self.soma.L = self.soma.diam = 12.6157 # microns self.dend.L = 200 # microns self.dend.diam = 1 # microns self.dend.nseg = 5 h.define_shape() # Translate into 3D points.
def fix_axon_perisomatic_directed(hobj): # io.log_info('Fixing Axon like perisomatic') all_sec_names = [] for sec in hobj.all: all_sec_names.append(sec.name().split(".")[1][:4]) if 'axon' not in all_sec_names: io.log_exception('There is no axonal recostruction in swc file.') else: beg1, end1, beg2, end2 = get_axon_direction(hobj) for sec in hobj.axon: h.delete_section(sec=sec) h.execute('create axon[2]', hobj) h.pt3dadd(beg1[0], beg1[1], beg1[2], 1, sec=hobj.axon[0]) h.pt3dadd(end1[0], end1[1], end1[2], 1, sec=hobj.axon[0]) hobj.all.append(sec=hobj.axon[0]) h.pt3dadd(beg2[0], beg2[1], beg2[2], 1, sec=hobj.axon[1]) h.pt3dadd(end2[0], end2[1], end2[2], 1, sec=hobj.axon[1]) hobj.all.append(sec=hobj.axon[1]) hobj.axon[0].connect(hobj.soma[0], 0.5, 0) hobj.axon[1].connect(hobj.axon[0], 1.0, 0) hobj.axon[0].L = 30.0 hobj.axon[1].L = 30.0 h.define_shape() for sec in hobj.axon: # print "sec.L:", sec.L if np.abs(30 - sec.L) > 0.0001: io.log_exception('Axon stub L is less than 30')
def geom(self): ''' Adds length and diameter to sections ''' for sec in self.node: sec.L = self.nodelength # microns sec.diam = self.nodeD # microns sec.nseg = 1 for sec in self.MYSA: sec.L = self.paralength1 # microns sec.diam = self.fiberD # microns sec.nseg = 1 for sec in self.FLUT: sec.L = self.paralength2 # microns sec.diam = self.fiberD # microns sec.nseg = 1 for sec in self.STIN: sec.L = self.interlength # microns sec.diam = self.fiberD # microns sec.nseg = 1 h.define_shape()
def move(self, offset=(0, 0, 0)): ox, oy, oz = offset[0], offset[1], offset[2] h.define_shape() xlo = ylo = zlo = xhi = yhi = zhi = None for sec in self.all: sec.nseg = 1 n3d = sec.n3d() xs = [sec.x3d(i) + ox for i in range(n3d)] ys = [sec.y3d(i) + oy for i in range(n3d)] zs = [sec.z3d(i) + oz for i in range(n3d)] ds = [sec.diam3d(i) for i in range(n3d)] sec.pt3dclear() for x, y, z, d in zip(xs, ys, zs, ds): sec.pt3dadd(x, y, z, d) my_xlo, my_ylo, my_zlo = min(xs), min(ys), min(zs) my_xhi, my_yhi, my_zhi = max(xs), max(ys), max(zs) if xlo is None: xlo, ylo, zlo = my_xlo, my_ylo, my_zlo xhi, yhi, zhi = my_xhi, my_yhi, my_zhi else: xlo, ylo, zlo = min(xlo, my_xlo), min(ylo, my_ylo), min(zlo, my_zlo) xhi, yhi, zhi = max(xhi, my_xhi), max(yhi, my_yhi), max(zhi, my_zhi) return xlo, ylo, zlo, xhi, yhi, zhi
def generate_morphology(self, morph_filename): """Instantiate a morphology from an SWC file at `morph_filename` Also deletes the axonal compartments from the SWC file and inserts an axonal "stub" in its place. """ cell = self.cell swc = self.h.Import3d_SWC_read() swc.quiet = 1 swc.input(morph_filename.encode('ascii', 'ignore')) imprt = self.h.Import3d_GUI(swc, 0) imprt.instantiate(cell) for seg in cell.soma[0]: seg.area() for sec in cell.all: sec.nseg = 1 + 2 * int(sec.L / 40) cell.simplify_axon() for sec in cell.axonal: sec.L = 30 sec.diam = 1 sec.nseg = 1 + 2 * int(sec.L / 40) cell.axon[0].connect(cell.soma[0], 0.5, 0) cell.axon[1].connect(cell.axon[0], 1, 0) h.define_shape()
def setup_pcmorphology(kk, x, y, z): print 'i value is:', kk cellpc = Purkinje() h.define_shape() sections = h.SectionList() sections.wholetree(cellpc.soma) cellpc.soma.push() n = h.n3d(sec=cellpc.soma) xs = [h.x3d(i) for i in range(int(n))] ys = [h.y3d(i) for i in range(int(n))] zs = [h.z3d(i) for i in range(int(n))] ds = [h.diam3d(i) for i in range(int(n))] j = 0 #sec.push() for a, b, c, d in zip(xs, ys, zs, ds): #print 'sec here is:', sec h.pt3dchange(j, a + x, b + y, c + z, d) j += 1 h.define_shape() h.pop_section() pulist.append(cellpc) #call another function to locate the local granule neurons cellpc.soma.push() getpurksecs = h.SectionList() getpurksecs.wholetree(cellpc.soma) func_local_grcneurons(kk, getpurksecs)
def get_coords_and_radii(self): nrn_section = self.nrn_section # Count 3D points point_count = int(h.n3d(sec=nrn_section)) # Let NEURON create them if missing if point_count == 0: h.define_shape(sec=self.nrn_section) point_count = int(h.n3d(sec=self.nrn_section)) # Collect the coordinates coords = [None] * point_count * 3 # 3 for xy and z radii = [None] * point_count for c in range(point_count): ci = c * 3 coords[ci] = h.x3d(c, sec=nrn_section) coords[ci + 1] = h.y3d(c, sec=nrn_section) coords[ci + 2] = h.z3d(c, sec=nrn_section) radii[c] = h.diam3d(c, sec=nrn_section) / 2.0 self.nseg = int(nrn_section.nseg) self.point_count = point_count self.coords = coords self.radii = radii
def insert(self): h = self.h if not hasattr(h, 'cvode'): h.load_file('stdrun.hoc') if not h.cvode.use_fast_imem(): h.cvode.use_fast_imem(1) h.init() if self.method == 'Point': LfpClass = SectionLfpPointMethod elif self.method == 'Line': LfpClass = SectionLfpLineMethod else: # self.method == 'RC': LfpClass = SectionLfpRCMethod for sec in self.sec_list: # h.allsec(): if self.is_lfp_section(sec.name()): # Let NEURON create 3D points if missing if h.n3d(sec=sec) <= 0: h.define_shape(sec=sec) # Keep track of sections being monitored self.section_lfps[sec] = LfpClass(self, sec)
def __init__(self, gid, x, y, z, theta): self._gid = gid self._setup_morphology() self._setup_biophysics() self.x = self.y = self.z = 0 h.define_shape() self._rotate_z(theta) self._set_position(x, y, z)
def define_geometry(self, soma_d, soma_l, dend_d, dend_l, dend_nseg): """Set the 3D geometry of the cell.""" self.soma.L = soma_l # microns self.soma.diam = soma_d # microns self.dend.L = dend_l # microns self.dend.diam = dend_d # microns self.dend.nseg = dend_nseg # number of divisions for dendrite h.define_shape() # Translate into 3D points.
def define_soma_at_root( self, neuron, rad = 2000, L = 2000): root_section = self.find_section_from_nodeid( neuron.root ) self.sections.append( h.Section(name='soma', cell=self) ) root_section.connect( self.sections[-1](1) ) self.sections[-1].L = L * 0.001 self.sections[-1].diam = 2*rad * 0.001 self.soma = self.sections[-1] h.define_shape()
def set_cell_position(self, x, y, z): h.define_shape() for sec in self.secs: for i in range(sec.n3d()): sec.pt3dchange(i, x - sec.x3d(i), y - sec.y3d(i), z - sec.z3d(i), sec.diam3d(i))
def __init__(self, c_id, x, y, z, theta): self.c_id = c_id self.x = self.y = self.z = 0 self._set_morphology() self.all = self.soma.wholetree() self._set_biophysics() h.define_shape() self._set_position(x, y, z) self._rotate_z(theta)
def defineCellShapes(self): from .. import sim if sim.cfg.createNEURONObj: sim.net.compartCells = [ c for c in sim.net.cells if type(c) is sim.CompartCell ] h.define_shape() for cell in sim.net.compartCells: cell.updateShape()
def get_data(data_dir, simulate_new=True, run_original=True): ''' returns the data from the simulations, depending on the params, it either runs new simulations or not. run_original = True -> original Hallermann model, False -> reduced Nav model''' if run_original: save_file = 'data_hallerman_raw_original.npz' else: save_file = 'data_hallerman_raw_redNav.npz' save_file = os.path.join(data_dir, save_file) if simulate_new: # params dt = 0.0125 sim_len = 60 # ms stim_delay = 40 # ms stim_dur = 1 # ms postfix = '' det = True if run_original: simulate_original_model(data_dir) # to simulate original model else: simulate_reduced_Nav_model(data_dir) # to simulate reduced Nav model st = add_stimulation(st_delay=stim_delay,st_dur=stim_dur, stim_delay=stim_delay) vecs_ais, vec_soma, vec_st = get_recording_vecs(st) # simulate the cell cell.initialize(dt=dt) cell.h.finitialize(-85) t, I, I_axial = cell.integrate(sim_len, i_axial=True) # extract the data v_soma = np.array(vec_soma) h.define_shape() seg_coords = cell.get_seg_coords() #!!!! Need of current correction areas = [] for sec in cell.h.allsec(): areas += [seg.area() for seg in sec] surface = np.pi * coords['diam'] * coords['L'] currents_with_electrode = currents_with_electrode * areas / surface #!!!!! # save the data time = (np.arange(len(v_soma))*dt) np.savez(save_file, I=I, t=time, I_axial=I_axial, v_soma=v_soma, seg_coords=seg_coords,vecs_ais=vecs_ais, dt=h.dt, stim_delay=stim_delay) data = np.load(save_file) return data
def _do_init1(self): from . import rxd # TODO: if a list of sections is passed in, make that one region # _species_count is used to create a unique _real_name for the species global _species_count regions = self.regions self._real_name = self._name initial = self.initial charge = self._charge # invalidate any old initialization of external solvers rxd._external_solver_initialized = False # TODO: check about the 0<x<1 problem alluded to in the documentation h.define_shape() name = self.name if name is not None: if not isinstance(name, str): raise RxDException('Species name must be a string') if name in _defined_species and _defined_species[name]() is not None: raise RxDException('Species "%s" previously defined: %r' % (name, _defined_species[name]())) else: name = _species_count self._id = _species_count _species_count += 1 _defined_species[name] = weakref.ref(self) if regions is None: raise RxDException('Must specify region where species is present') if hasattr(regions, '__len__'): regions = list(regions) else: regions = list([regions]) # TODO: unite handling of _regions and _extracellular_regions self._regions = [r for r in regions if not isinstance(r, region.Extracellular)] self._extracellular_regions = [r for r in regions if isinstance(r, region.Extracellular)] if not all(isinstance(r, region.Region) for r in self._regions): raise RxDException('regions list must consist of Region and Extracellular objects only') if self._extracellular_regions: # make sure that the extracellular callbacks are configured, if necessary _ensure_extracellular() self._species = weakref.ref(self) # at this point self._name is None if unnamed or a string == name if # named self._ion_register() # TODO: remove this line when certain no longer need it (commented out 2013-04-17) # self._real_secs = region._sort_secs(sum([r.secs for r in regions], [])) #Set the SpeciesOnRegion id for sp in _species_on_regions: s = sp() if s and s._species() == self: s._id = self._id
def define_geometry(self): ''' Adds length and diameter to sections ''' for sec in self.stimsec: sec.L = self.L# microns sec.diam = self.diam # microns self.branch.L = self.L self.branch.diam = self.diam self.branch.nseg = 1 h.define_shape() # Translate into 3D points.
def define_geometry(self): ''' Adds length and diameter to sections ''' for sec in self.stimsec: sec.L = self.L# microns sec.diam = self.diam # microns self.branch.L = self.L self.branch.diam = self.diam self.branch.nseg = 1 h.define_shape() # Translate into 3D points.
def _init(): # TODO: check about the 0<x<1 problem alluded to in the documentation h.define_shape() section1d._purge_cptrs() for sr in species._get_all_species().values(): s = sr() if s is not None: s._register_cptrs() s._finitialize() _setup_matrices()
def rotate_cell_z(self, theta): h.define_shape() """Rotate the cell about the Z axis.""" for sec in self.secs: for i in range(sec.n3d()): x = sec.x3d(i) y = sec.y3d(i) c = h.cos(theta) s = h.sin(theta) xprime = x * c - y * s yprime = x * s + y * c sec.pt3dchange(i, xprime, yprime, sec.z3d(i), sec.diam3d(i))
def _init(): # TODO: check about the 0<x<1 problem alluded to in the documentation h.define_shape() section1d._purge_cptrs() for sr in species._get_all_species().values(): s = sr() if s is not None: s._register_cptrs() s._finitialize() _setup_matrices()
def define_geometry(self, dl, dd, sl, sd, hl, hd, ail, aid, axl, axd): # Set the geometry of the neuron self.dend1.L = self.dend1.nseg = dl # microns self.dend1.diam = dd self.soma.L = self.soma.nseg = sl self.soma.diam = sd self.hill.L = self.hill.nseg = hl self.hill.diam = hd self.ais.L = self.ais.nseg = ail self.ais.diam = aid self.axon.L = self.axon.nseg = axl self.axon.diam = axd h.define_shape() # translate into 3D points
def fix_axon_peri_v2(hobj): """Replace reconstructed axon with a stub :param hobj: hoc object """ for i, sec in enumerate(hobj.axon): if i < 2: sec.L = 30 sec.diam = 1 else: sec.L = 1e-6 sec.diam = 1 h.define_shape()
def _do_reset_geometry(): h.define_shape() secs = list(h.allsec()) geo = [] for sec in secs: geo += _segment_3d_pts(sec) javascript_embedder(("set_neuron_section_data(%s);" % json.dumps(geo))) for sp in _shape_plot_list: sp = sp() if sp is not None: sp._reload_morphology() # could probably get rid of this, but slower response sp._force_redraw = True del secs
def draw_model(self): """Draw the model. Params: controls - the main gui obj.""" # Draw the new one h.define_shape() num_sections = 0 # Disable the render. Faster drawing. self.mayavi.visualization.scene.disable_render = True x,y,z,d = [], [], [], [] voltage = [] connections = [] for sec in h.allsec(): x_sec, y_sec, z_sec, d_sec = self.retrieve_coordinate(sec) self.sec2coords[sec.name()] = [x_sec, y_sec, z_sec] # Store the section. later. radius = sec.diam/2. sec_coords_bound = ((x_sec.min(), x_sec.max()), (y_sec.min() - radius, y_sec.max() + radius), (z_sec.min() - radius, z_sec.max() + radius)) self.cyl2sec[sec_coords_bound] = sec self.sec2cyl[sec] = sec_coords_bound for i,xi in enumerate(x_sec): x.append(x_sec[i]) y.append(y_sec[i]) z.append(z_sec[i]) d.append(d_sec[i]) indx_geom_seg = len(x) -1 if len(x) > 1 and i > 0: connections.append([indx_geom_seg, indx_geom_seg-1]) self.edges = connections self.x = x self.y = y self.z = z # Mayavi pipeline d = np.array(d) # Transforming for easy division self.draw_mayavi(x, y, z, d, self.edges)
def _do_updates(): global _last_diam_change_count, _last_structure_change_count while True: old_diam_changed = h.diam_changed h.define_shape() if old_diam_changed or h.diam_changed or _diam_change_count.value != _last_diam_change_count or _structure_change_count.value != _last_structure_change_count: h.diam_changed = 0 _last_diam_change_count = _diam_change_count.value _last_structure_change_count = _structure_change_count.value _do_reset_geometry() for obj in _gui_widgets: obj = obj() if obj is not None and obj._ready: obj._update() time.sleep(update_interval)
def _init(): initializer._do_init() # TODO: check about the 0<x<1 problem alluded to in the documentation h.define_shape() if species._has_1d: section1d._purge_cptrs() for sr in list(_species_get_all_species().values()): s = sr() if s is not None: # TODO: are there issues with hybrid or 3D here? (I don't think so, but here's a bookmark just in case) s._register_cptrs() s._finitialize() _setup_matrices()
def _load_geometry(self): '''Load the morphology-file in NEURON''' try: h.sec_counted = 0 except LookupError: h('sec_counted = 0') #import the morphology, try and determine format fileEnding = self.morphology.split('.')[-1] if fileEnding == 'hoc' or fileEnding == 'HOC': h.load_file(1, self.morphology) elif fileEnding == 'py': geom_func = imp.load_source('shape_3D', self.morphology) geom_func.shape_3D(self) else: neuron.h('objref this') if fileEnding == 'asc' or fileEnding == 'ASC': Import = h.Import3d_Neurolucida3() if not self.verbose: Import.quiet = 1 elif fileEnding == 'swc' or fileEnding == 'SWC': Import = h.Import3d_SWC_read() elif fileEnding == 'xml' or fileEnding == 'XML': Import = h.Import3d_MorphML() else: raise ValueError('%s is not a recognised morphology file format!' ).with_traceback( 'Should be either .hoc, .asc, .swc, .xml!' %self.morphology) #assuming now that morphologies file is the correct format try: Import.input(self.morphology) except: if not hasattr(neuron, 'neuroml'): raise Exception('Can not import, try and copy the ' + \ 'nrn/share/lib/python/neuron/neuroml ' + \ 'folder into %s' % neuron.__path__[0]) else: raise Exception('something wrong with file, see output') try: imprt = neuron.h.Import3d_GUI(Import, 0) except: raise Exception('See output, try to correct the file') imprt.instantiate(neuron.h.this) h.define_shape() self._create_sectionlists()
def re_init(): """reinitializes all rxd concentrations to match HOC values, updates matrices""" h.define_shape() # update current pointers section1d._purge_cptrs() for sr in species._get_all_species().values(): s = sr() if s is not None: s._register_cptrs() # update matrix equations _setup_matrices() for sr in species._get_all_species().values(): s = sr() if s is not None: s.re_init() _cvode_object.re_init()
def _save_geom(self, h5file_holder): """Store the NeuroML in the geometry table""" # writing the NeuroML model h.define_shape() # We need the 3D points h.load_file('mview.hoc') modelView = h.ModelView(0) modelXml = h.ModelViewXML(modelView) tmp_file = 'temp.xml' modelXml.xportLevel1(tmp_file) xml_data = '' with open(tmp_file, 'r') as f: xml_data = f.read() geom_group = h5file_holder.createGroup('/', self.geometry_root) h5file_holder.createArray(geom_group, self.geometry_node_name, xml_data) os.remove(tmp_file)
def generate_morphology(self, cell, morph_filename): ''' This code is from the Allen Brain API examples. This code is no longer executed. morph4.hoc is executed instead. ''' h = self.h swc = self.h.Import3d_SWC_read() swc.input(morph_filename) imprt = self.h.Import3d_GUI(swc, 0) h('execute("forall delete_section()",cell)') imprt.instantiate(cell) for seg in cell.soma[0]: seg.area() for sec in cell.allsec(): sec.nseg = 1 + 2 * int(sec.L / 40) h.define_shape()
def _do_init1(self): from . import rxd # TODO: if a list of sections is passed in, make that one region # _species_count is used to create a unique _real_name for the species global _species_count regions = self._regions self._real_name = self._name initial = self.initial charge = self._charge # invalidate any old initialization of external solvers rxd._external_solver_initialized = False # TODO: check about the 0<x<1 problem alluded to in the documentation h.define_shape() name = self.name if name is not None: if not isinstance(name, str): raise RxDException('Species name must be a string') if name in _defined_species and _defined_species[name]() is not None: raise RxDException('Species "%s" previously defined: %r' % (name, _defined_species[name]())) else: name = _species_count self._id = _species_count _species_count += 1 _defined_species[name] = weakref.ref(self) if regions is None: raise RxDException('Must specify region where species is present') if hasattr(regions, '__len__'): regions = list(regions) else: regions = list([regions]) self._regions = regions if not all(isinstance(r, region.Region) for r in regions): raise RxDException('regions list must consist of Region objects only') self._species = weakref.ref(self) # at this point self._name is None if unnamed or a string == name if # named self._ion_register()
def gcs(self,NCELL): ''' Instantiate NEURON cell Objects in the Python variable space such that all cells have unique identifiers. ''' NCELL=self.NCELL SIZE=self.SIZE RANK=self.RANK #from neuron import h pc=h.ParallelContext() h('objref nc, cells') swcdict={} NFILE = 3175 bothtrans=self.both_trans(self.prep_list()) self.names_list=[0 for x in xrange(0,len(bothtrans))] os.chdir(os.getcwd() + '/swclist') self.make_cells(bothtrans) os.chdir(os.getcwd() + '/../') h.define_shape() h('forall{ for(x,0){ insert xtra }}') h('forall{ for(x,0){ insert extracellular}}') h('xopen("interpxyz.hoc")') h('grindaway()')
def re_init(): """reinitializes all rxd concentrations to match HOC values, updates matrices""" global _external_solver_initialized h.define_shape() if not species._has_3d: # TODO: if we do have 3D, make sure that we do the necessary parts of this # update current pointers section1d._purge_cptrs() for sr in list(_species_get_all_species().values()): s = sr() if s is not None: s._register_cptrs() # update matrix equations _setup_matrices() for sr in list(_species_get_all_species().values()): s = sr() if s is not None: s.re_init() # TODO: is this safe? _cvode_object.re_init() _external_solver_initialized = False
def constructive_neuronal_geometry(source, n_soma_step, dx): objects = [] source_is_import3d = False # TODO: come up with a better way of checking type if hasattr(source, 'sections'): source_is_import3d = True cell = source # probably an Import3D type num_contours = sum(sec.iscontour_ for sec in cell.sections) if num_contours > 1: raise Exception('more than one contour is not currently supported') if num_contours == 1: # setup the soma # CTNG:soma branches = [] parent_sec_name = [] for sec in cell.sections: if sec.iscontour_: soma_sec = sec.hname() x, y, z = [sec.raw.getrow(i).to_python() for i in xrange(3)] # compute the center of the contour based on uniformly spaced points around the perimeter center_vec = sec.contourcenter(sec.raw.getrow(0), sec.raw.getrow(1), sec.raw.getrow(2)) x0, y0, z0 = [center_vec.x[i] for i in xrange(3)] somax, somay, somaz = x0, y0, z0 xshifted = [xx - x0 for xx in x] yshifted = [yy - y0 for yy in y] # this is a hack to pretend everything is on the same z level zshifted = [0] * len(x) # locate the major and minor axis, adapted from import3d_gui.hoc m = h.Matrix(3, 3) for i, p in enumerate([xshifted, yshifted, zshifted]): for j, q in enumerate([xshifted, yshifted, zshifted]): if j < i: continue v = numpy.dot(p, q) m.setval(i, j, v) m.setval(j, i, v) # CTNG:majoraxis tobj = m.symmeig(m) # major axis is the one with largest eigenvalue major = m.getcol(tobj.max_ind()) # minor is normal and in xy plane minor = m.getcol(3 - tobj.min_ind() - tobj.max_ind()) #minor.x[2] = 0 minor.div(minor.mag()) x1 = x0; y1 = y0 x2 = x1 + major.x[0]; y2 = y1 + major.x[1] xs_loop = x + [x[0]] ys_loop = y + [y[0]] # locate the extrema of the major axis CTNG:somaextrema # this is defined by the furthest points on it that lie on the minor axis pts = [] pts_sources = {} for x3, y3 in zip(x, y): x4, y4 = x3 + minor.x[0], y3 + minor.x[1] pt = seg_line_intersection(x1, y1, x2, y2, x3, y3, x4, y4, clip=False) if pt is not None: pts.append(pt) if pt not in pts_sources: pts_sources[pt] = [] pts_sources[pt].append((x3, y3)) major_p1, major_p2 = extreme_pts(pts) extreme1 = pts_sources[major_p1] extreme2 = pts_sources[major_p2] major_p1, major_p2 = numpy.array(major_p1), numpy.array(major_p2) del pts_sources if len(extreme1) != 1 or len(extreme2) != 1: raise Exception('multiple most extreme points') extreme1 = extreme1[0] extreme2 = extreme2[0] major_length = linalg.norm(major_p1 - major_p2) delta_x, delta_y = major_p2 - major_p1 delta_x /= n_soma_step delta_y /= n_soma_step f_pts = [major_p1] f_diams = [0] # CTNG:slicesoma for i in xrange(1, n_soma_step): x0, y0 = major_p1[0] + i * delta_x, major_p1[1] + i * delta_y # slice in dir of minor axis x1, y1 = x0 + minor.x[0], y0 + minor.x[1] pts = [] for i in xrange(len(x)): pt = seg_line_intersection(xs_loop[i], ys_loop[i], xs_loop[i + 1], ys_loop[i + 1], x0, y0, x1, y1, clip=True) if pt is not None: pts.append(pt) p1, p2 = extreme_pts(pts) p1, p2 = numpy.array(p1), numpy.array(p2) cx, cy = (p1 + p2) / 2. f_pts.append((cx, cy)) f_diams.append(linalg.norm(p1 - p2)) f_pts.append(major_p2) f_diams.append(0) for i in xrange(len(f_pts) - 1): pt1x, pt1y = f_pts[i] pt2x, pt2y = f_pts[i + 1] diam1 = f_diams[i] diam2 = f_diams[i + 1] objects.append(SkewCone(pt1x, pt1y, z0, diam1 * 0.5, pt1x + delta_x, pt1y + delta_y, z0, diam2 * 0.5, pt2x, pt2y, z0)) else: parent_sec_name.append(sec.parentsec.hname()) branches.append(sec) else: h.define_shape() soma_sec = None branches = [] for sec in source: branches.append(sec) # this is ignored in this case, but needs to be same length # so this way no extra memory except the pointer parent_sec_name = branches ##################################################################### # # add the branches # ##################################################################### diam_corrections = {None: None} while diam_corrections: all_cones = [] pts_cones_db = {} diam_db = {} for branch, psec in zip(branches, parent_sec_name): if source_is_import3d: x, y, z = [branch.raw.getrow(i).to_python() for i in xrange(3)] d = branch.d.to_python() else: x = [h.x3d(i, sec=branch) for i in xrange(int(h.n3d(sec=branch)))] y = [h.y3d(i, sec=branch) for i in xrange(int(h.n3d(sec=branch)))] z = [h.z3d(i, sec=branch) for i in xrange(int(h.n3d(sec=branch)))] d = [h.diam3d(i, sec=branch) for i in xrange(int(h.n3d(sec=branch)))] # make sure that all the ones that connect to the soma do in fact connect # do this by connecting to local center axis # CTNG:connectdends if psec == soma_sec: pt = (x[1], y[1], z[1]) cp = closest_pt(pt, f_pts, somaz) # NEURON includes the wire point at the center; we want to connect # to the closest place on the soma's axis instead with full diameter x, y, z, d = [cp[0]] + [X for X in x[1 :]], [cp[1]] + [Y for Y in y[1:]], [somaz] + [Z for Z in z[1:]], [d[1]] + [D for D in d[1 :]] for i in xrange(len(x) - 1): d0, d1 = d[i : i + 2] if (x[i] != x[i + 1] or y[i] != y[i + 1] or z[i] != z[i + 1]): # short section check #if linalg.norm((x[i + 1] - x[i], y[i + 1] - y[i], z[i + 1] - z[i])) < (d1 + d0) * 0.5: # short_segs += 1 axisx, axisy, axisz, deltad = x[i + 1] - x[i], y[i + 1] - y[i], z[i + 1] - z[i], d1 - d0 axislength = (axisx ** 2 + axisy ** 2 + axisz ** 2) ** 0.5 axisx /= axislength; axisy /= axislength; axisz /= axislength; deltad /= axislength x0, y0, z0 = x[i], y[i], z[i] x1, y1, z1 = x[i + 1], y[i + 1], z[i + 1] if (x0, y0, z0) in diam_corrections: d0 = diam_corrections[(x0, y0, z0)] if (x1, y1, z1) in diam_corrections: d1 = diam_corrections[(x1, y1, z1)] if d0 != d1: all_cones.append(Cone(x0, y0, z0, d0 * 0.5, x1, y1, z1, d1 * 0.5)) else: all_cones.append(Cylinder(x0, y0, z0, x1, y1, z1, d1 * 0.5)) register(pts_cones_db, (x0, y0, z0), all_cones[-1]) register(pts_cones_db, (x1, y1, z1), all_cones[-1]) register(diam_db, (x0, y0, z0), d0) register(diam_db, (x1, y1, z1), d1) # at join, should always be the size of the biggest branch # this is different behavior than NEURON, which continues the size of the # first point away from the join to the join diam_corrections = {} for pt in diam_db: vals = diam_db[pt] if max(vals) != min(vals): diam_corrections[pt] = max(vals) cone_clip_db = {cone: [] for cone in all_cones} join_counts = {'2m': 0, '2s': 0, '3m': 0, '3s': 0, '4m': 0, '4s': 0, '0m': 0, '0s': 0, '1m': 0, '1s': 0} for cone in all_cones: x1, y1, z1, r1 = cone._x0, cone._y0, cone._z0, cone._r0 x2, y2, z2, r2 = cone._x1, cone._y1, cone._z1, cone._r1 pt1 = numpy.array([x1, y1, z1]) pt2 = numpy.array([x2, y2, z2]) axis = (pt2 - pt1) / linalg.norm(pt2 - pt1) left_neighbors = list(pts_cones_db[(x1, y1, z1)]) right_neighbors = list(pts_cones_db[(x2, y2, z2)]) left_neighbors.remove(cone) right_neighbors.remove(cone) if not left_neighbors: left_neighbors = [None] if not right_neighbors: right_neighbors = [None] for neighbor_left, neighbor_right in itertools.product(left_neighbors, right_neighbors): clips = [] # process the join on the "left" (end 1) if neighbor_left is not None: # any joins are created on the left pass; the right pass will only do clippings x0, y0, z0, r0 = neighbor_left._x0, neighbor_left._y0, neighbor_left._z0, neighbor_left._r0 if x0 == x1 and y0 == y1 and z0 == z1: x0, y0, z0, r0 = neighbor_left._x1, neighbor_left._y1, neighbor_left._z1, neighbor_left._r1 pt0 = numpy.array([x0, y0, z0]) naxis = (pt1 - pt0) / linalg.norm(pt1 - pt0) # no need to clip if the cones are perfectly aligned if any(axis != naxis): if r0 == r1 == r2: # simplest join: two cylinders (no need for all that nastiness below) sp = Sphere(x1, y1, z1, r1) sp.set_clip([Plane(x0, y0, z0, -naxis[0], -naxis[1], -naxis[2]), Plane(x2, y2, z2, axis[0], axis[1], axis[2])]) objects.append(sp) else: # is the turn sharp or not # CTNG:joinangle sharp_turn = numpy.dot(axis, naxis) < 0 # locate key vectors plane_normal = numpy.cross(axis, naxis) radial_vec = numpy.cross(plane_normal, axis) nradial_vec = numpy.cross(plane_normal, naxis) # normalize all of these radial_vec /= linalg.norm(radial_vec) nradial_vec /= linalg.norm(nradial_vec) # count the corners that are inside the other cone (for both ways) # CTNG:outsidecorners my_corner_count = count_outside(neighbor_left, [pt1 + r1 * radial_vec, pt1 - r1 * radial_vec]) corner_count = my_corner_count + count_outside(cone, [pt1 + r1 * nradial_vec, pt1 - r1 * nradial_vec]) # if corner_count == 0, then probably all nan's from size 0 meeting size 0; ignore # if is 1, probably parallel; no joins # if corner_count not in (1, 2, 3, 4): # print 'corner_count: ', corner_count, [pt1 + r1 * radial_vec, pt1 - r1 * radial_vec] + [pt1 + r1 * nradial_vec, pt1 - r1 * nradial_vec] if corner_count == 2: # CTNG:2outside # add clipped sphere; same rule if sharp or mild turn objects += join_outside(x0, y0, z0, r0, x1, y1, z1, r1, x2, y2, z2, r2, dx) elif corner_count == 3: sp = Sphere(x1, y1, z1, r1) if sharp_turn: # CTNG:3outobtuse if my_corner_count == 1: sp.set_clip([Plane(x1, y1, z1, -naxis[0], -naxis[1], -naxis[2])]) else: sp.set_clip([Plane(x1, y1, z1, axis[0], axis[1], axis[2])]) objects.append(sp) else: # CTNG:3outacute objects += join_outside(x0, y0, z0, r0, x1, y1, z1, r1, x2, y2, z2, r2, dx) if my_corner_count == 1: objects.append(tangent_sphere(neighbor_left, 1)) objects[-1].set_clip([Plane(x2, y2, z2, naxis[0], naxis[1], naxis[2])]) else: objects.append(tangent_sphere(cone, 0)) objects[-1].set_clip([Plane(x0, y0, z0, -axis[0], -axis[1], -axis[2])]) elif corner_count == 4: sp = Sphere(x1, y1, z1, r1) if sharp_turn: # CTNG:4outobtuse # join with the portions of a sphere that are outside at least one of the planes sp.set_clip([Union([ Plane(x1, y1, z1, axis[0], axis[1], axis[2]), Plane(x1, y1, z1, -naxis[0], -naxis[1], -naxis[2])])]) objects.append(sp) else: # CTNG:4outacute (+ 1 more) # join with the portions of a sphere that are outside both planes objects += join_outside(x0, y0, z0, r0, x1, y1, z1, r1, x2, y2, z2, r2, dx) # AND clip the cone to not extend pass the union of the neighbor's plane and the neighbor if r0 == r1: neighbor_copy = Cylinder(x0, y0, z0, x1, y1, z1, r0) else: neighbor_copy = Cone(x0, y0, z0, r0, x1, y1, z1, r1) clips.append(Union([ Plane(x1, y1, z1, -naxis[0], -naxis[1], -naxis[2]), neighbor_copy])) join_type = '%d%s' % (corner_count, 's' if sharp_turn else 'm') join_counts[join_type] += 1 if neighbor_right is not None: # any joins are created on the left pass; the right pass will only do clippings x3, y3, z3, r3 = neighbor_right._x0, neighbor_right._y0, neighbor_right._z0, neighbor_right._r0 if x2 == x3 and y2 == y3 and z2 == z3: x3, y3, z3, r3 = neighbor_right._x1, neighbor_right._y1, neighbor_right._z1, neighbor_right._r1 pt3 = numpy.array([x3, y3, z3]) naxis = (pt3 - pt2) / linalg.norm(pt3 - pt2) # no need to clip if the cones are perfectly aligned if any(axis != naxis): # locate key vectors plane_normal = numpy.cross(axis, naxis) radial_vec = numpy.cross(plane_normal, axis) radial_vec_norm = linalg.norm(radial_vec) # we check again because sometimes there are roundoff errors that this catches if radial_vec_norm: # is the turn sharp or not sharp_turn = numpy.dot(axis, naxis) < 0 nradial_vec = numpy.cross(plane_normal, naxis) # normalize all of these radial_vec /= radial_vec_norm nradial_vec /= linalg.norm(nradial_vec) # count the corners that are inside the other cone (for both ways) my_corner_count = count_outside(neighbor_right, [pt2 + r2 * radial_vec, pt2 - r2 * radial_vec]) corner_count = my_corner_count + count_outside(cone, [pt2 + r2 * nradial_vec, pt2 - r2 * nradial_vec]) if corner_count == 2: # no clipping; already joined pass elif corner_count == 3: pass elif corner_count == 4: # CTNG:4outacute (+ 1 more) # already joined; just clip (only in mild turn case) if not sharp_turn: if r2 == r3: neighbor_copy = Cylinder(x2, y2, z2, x3, y3, z3, r3) else: neighbor_copy = Cone(x2, y2, z2, r2, x3, y3, z3, r3) #print 'cc=4: (%g, %g, %g; %g) (%g, %g, %g; %g) (%g, %g, %g; %g) ' % (x1, y1, z1, r1, x2, y2, z2, r2, x3, y3, z3, r3) clips.append(Union([ Plane(x2, y2, z2, naxis[0], naxis[1], naxis[2]), neighbor_copy])) if clips: cone_clip_db[cone].append(Intersection(clips)) #print 'join_counts:' #print join_counts for cone in all_cones: clip = cone_clip_db[cone] if clip: cone.set_clip([Union(clip)]) ##################################################################### # # add the clipped objects to the list # ##################################################################### objects += all_cones return objects
def __init__(self, regions=None, d=0, name=None, charge=0, initial=None): """s = rxd.Species(regions, d = 0, name = None, charge = 0, initial = None) Declare a species. Parameters: regions -- a Region or list of Region objects containing the species d -- the diffusion constant of the species (optional; default is 0, i.e. non-diffusing) name -- the name of the Species; used for syncing with HOC (optional; default is none) charge -- the charge of the Species (optional; default is 0) initial -- the initial concentration or None (if None, then imports from HOC if the species is defined at finitialize, else 0) Note: charge must match the charges specified in NMODL files for the same ion, if any.""" # TODO: if a list of sections is passed in, make that one region # _species_count is used to create a unique _real_name for the species global _species_count # TODO: check about the 0<x<1 problem alluded to in the documentation h.define_shape() self._name = name if name is not None: if not isinstance(name, str): raise Exception('Species name must be a string') if name in _defined_species and _defined_species[name]() is not None: raise Exception('Species "%s" previously defined: %r' % (name, _defined_species[name]())) else: name = _species_count self._id = _species_count _species_count += 1 _defined_species[name] = weakref.ref(self) if regions is None: raise Exception('Must specify region where species is present') if hasattr(regions, '__len__'): regions = list(regions) else: regions = list([regions]) if not all(isinstance(r, region.Region) for r in regions): raise Exception('regions list must consist of Region objects only') self._regions = regions self._real_name = name self.initial = initial self._charge = charge self._d = d # at this point self._name is None if unnamed or a string == name if # named if self._name is not None: ion_type = h.ion_register(name, charge) if ion_type == -1: raise Exception('Unable to register species: %s' % species) # insert the species if not already present for r in regions: if r.nrn_region in ('i', 'o'): for s in r.secs: try: ion_forms = [name + 'i', name + 'o', 'i' + name, 'e' + name] for i in ion_forms: # this throws an exception if one of the ion forms is missing temp = s.__getattribute__(name + 'i') except: s.insert(name + '_ion') # set to recalculate reversal potential automatically # the last 1 says to set based on global initial concentrations # e.g. nai0_na_ion, etc... h.ion_style(name + '_ion', 3, 2, 1, 1, 1, sec=s) self._real_secs = region._sort_secs(sum([r.secs for r in regions], [])) # TODO: at this point the sections are sorted within each region, but for # tree solver (which not currently using) would need sorted across # all regions if diffusion between multiple regions self._secs = [Section1D(self, sec, d, r) for r in regions for sec in r.secs] if self._secs: self._offset = self._secs[0]._offset else: self._offset = 0 self._has_adjusted_offsets = False self._assign_parents() self._update_region_indices()