Exemple #1
0
 def f(x):
     y = x**2
     if invoke:
         if h.cas() == dend and x == 1.0:
             1 / 0
         if h.cas() == dend and x > 0.6:
             sys.exit(0)
     print("{}({})".format(h.cas(), x))
     return y
Exemple #2
0
 def testSectionListIterator(self):
     """As of v8.0, iteration over a SectionList does not change the cas"""
     # See issue 509. SectionList iterator bug requires change to
     # longstanding behavior
     soma = h.Section(name='soma')
     soma.push()
     sections = [h.Section(name='s%d' % i) for i in range(3)]
     assert len([s for s in h.allsec()]) == 4
     sl = h.SectionList(sections)
     # Iteration over s SectionList does not change the currently accessed section
     for s in sl:
         assert 1 and h.cas() == soma
     # If an iteration does not complete the section stack is still ok.
     assert sections[1] in sl
     assert 2 and h.cas() == soma
Exemple #3
0
 def setup(self):
     h.cvode.use_fast_imem(
         1
     )  # enables fast calculation of transmembrane current (nA) at each segment
     self.bscallback = h.beforestep_callback(h.cas()(.5))
     self.bscallback.set_callback(self.callback)
     fih = h.FInitializeHandler(1, self.LFPinit)
Exemple #4
0
def importCell (fileName, cellName, cellArgs = None, cellInstance = False):
    h.initnrn()
    varList = mechVarList()  # list of properties for all density mechanisms and point processes
    origGlob = getGlobals(list(varList['mechs'].keys())+list(varList['pointps'].keys()))
    origGlob['v_init'] = -65  # add by hand since won't be set unless load h.load_file('stdrun')

    if cellArgs is None: cellArgs = [] # Define as empty list if not otherwise defined

    ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)'''
    if fileName.endswith('.hoc') or fileName.endswith('.tem'):
        h.load_file(fileName)
        if not cellInstance:
            if isinstance(cellArgs, dict):
                cell = getattr(h, cellName)(**cellArgs)  # create cell using template, passing dict with args
            else:
                cell = getattr(h, cellName)(*cellArgs) # create cell using template, passing list with args
        else:
            try:
                cell = getattr(h, cellName)
            except:
                cell = None
    elif fileName.endswith('.py'):
        filePath,fileNameOnly = os.path.split(fileName)  # split path from filename
        if filePath not in sys.path:  # add to path if not there (need to import module)
            sys.path.insert(0, filePath)
            removeFilePath = True
        else:
            removeFilePath = False
        moduleName = fileNameOnly.split('.py')[0]  # remove .py to obtain module name
        tempModule = importlib.import_module(moduleName)
        modulePointer = tempModule
        if isinstance(cellArgs, dict):
            cell = getattr(modulePointer, cellName)(**cellArgs) # create cell using template, passing dict with args
        else:
            cell = getattr(modulePointer, cellName)(*cellArgs)  # create cell using template, passing list with args
        if removeFilePath: sys.path.remove(filePath)
    else:
        print("File name should be either .hoc or .py file")
        return

    secDic, secListDic, synMechs, globs = getCellParams(cell, varList, origGlob)
    
    if fileName.endswith('.py'):
        _delete_module(moduleName)
        _delete_module('tempModule')
        del modulePointer
    elif fileName.endswith('.hoc'):
        for sec in h.allsec():
            try:
                if h.cas()!=sec: sec.push()
                h.delete_section()
                h.pop_section()
            except:
                pass
    h.initnrn()

    setGlobals(origGlob)  # restore original globals

    return secDic, secListDic, synMechs, globs
Exemple #5
0
 def _get_syn_location(self, nc, cell):
     if isinstance(cell, BioCell):
         sec_x = nc.postloc()
         sec = h.cas()
         sec_id = self._sec_lookup[cell.gid][
             sec]  # cell.get_section_id(sec)
         h.pop_section()
         return sec_id, sec_x
     else:
         return -1, -1
Exemple #6
0
    def _print_nc(self, nc, src_nid, trg_nid, cell, src_pop, trg_pop,
                  edge_type_id):
        if isinstance(cell, BioCell):
            sec_x = nc.postloc()
            sec = h.cas()
            sec_id = self._sec_lookup[cell.gid][
                sec]  # cell.get_section_id(sec)
            h.pop_section()
            self._syn_writer.add_bio_conn(edge_type_id, src_nid, src_pop,
                                          trg_nid, trg_pop, nc.weight[0],
                                          sec_id, sec_x)

        else:
            self._syn_writer.add_point_conn(edge_type_id, src_nid, src_pop,
                                            trg_nid, trg_pop, nc.weight[0])
Exemple #7
0
    def pre_synapse(self,j):
        '''
        search for viable synaptic vesicle sites.
        '''
        #from neuron import h   
        pc=h.ParallelContext()
        shiplist=[]
        h('objref coords') 
        h('coords = new Vector(3)')
        #self.celldict.items()[0]
        if j in self.celldict.keys():
            seglist= iter( (seg, sec, self.celldict[j]) for sec in self.celldict[j].spk_trig_ls for seg in sec )     
            for (seg,sec, cellc) in seglist:
                sec.push()
                get_cox = str('coords.x[0]=x_xtra('
                              + str(seg.x) + ')')
                h(get_cox)                   
                get_coy = str('coords.x[1]=y_xtra('
                              + str(seg.x) + ')')
                h(get_coy)
                get_coz = str('coords.x[2]=z_xtra('
                              + str(seg.x) + ')')
                h(get_coz)
                coordict={} 
                coordict['hostfrom'] = pc.id()
                coordict['coords'] = np.array(h.coords.to_python(),
                                          dtype=np.float64)
                coordict['gid']= int(j)
                coordict['seg']= seg.x                    
                secnames = h.cas().name()#sec.name()  
                coordict['secnames'] = str(secnames)
                shiplist.append(coordict)
                h.pop_section()

        '''                
        total_matrix=np.matrix(( 3,len(shiplist) ))
        total_list=[ (x['coords'][0],x['coords'][1],x['coords'][2]) for x in shiplist ]
        for i,j in enumerate(total_list):
            print type(j)
            #pdb.set_trace()
            total_matrix[i][0]=j[0]
            total_matrix[i][1]=j[1]
            total_matrix[i][2]=j[2]

        print total_array[:]
        '''
        
        return shiplist
Exemple #8
0
def f(a, b, c, d):
    l = list()
    print h.cas().name()
    l.append(h.NetCon(a, b, 0, 0, 1))
    soma3.push()
    print h.cas().name()
    l.append(h.NetCon(c, d, 0, 0, 1))
    h.pop_section()
    print h.cas().name()
    return l
Exemple #9
0
def connect(v1, syn2, v3, syn4):
    l = list()
    print h.cas().name()
    l.append(h.NetCon(v1, syn2, 0, 0, 0.5))
    soma3.push()
    print h.cas().name()
    l.append(h.NetCon(v3, syn4, 0, 0, 1))
    h.pop_section()
    print h.cas().name()
    return l
Exemple #10
0
def p(type, x, y, keystate):
    if type == 2:
        d = vc.nearest(x, y)
        arc = vc.push_selected()
        if arc >= 0:
            cs = h.cas()
            #vc.color(2)
            sn = str(cs)
            match = re.search('\.(dend|soma)\d*\Z', sn)
            if not match == None:
                name = match.group(0)[5:]
                print '%g from %s' % (d, name)
                print "at x=", x, ", y=", y
                vc.label(x, y, name, 1, 1, 0.5, 0., 5, 2)
                #vc.label(x+378.941,y+457.031,name,1,1,0.5,0.5,2)
                #vc.exec_menu("Change Text")
        h.pop_section()
        vc.flush()
Exemple #11
0
 def callback(self, type, x, y, keystate):
     #info about nearest section to mouse
     if type == 2:
         s = self.sh
         d = s.nearest(x, y)
         arc = s.push_selected()
         if arc >= 0:
             s.select()
             sec = h.cas()
             gid = self.sections[sec]
             ilayer, icircle, ipt = gid2org(gid)
             x, y, z = xyz(ilayer, icircle, ipt)
             print(
                 "gid %d   id (%d, %d, %d) prox pt at (%g, %g, %g) length %g"
                 % (gid, ilayer, icircle, ipt, x, y, z, sec.L))
             h.pop_section()
             if self.master:
                 neighborhood(ilayer, icircle, ipt)
Exemple #12
0
 def addvar(self, label, var=None):
     default_lab = False
     if var is None:
         var = label
         default_lab = True
     current_uuid = uuid.uuid4().hex
     if (isinstance(var, str)):  #retrieve cas
         spl = var.split('(')
         if len(spl) == 1:
             seg = 0.5  #default
         else:
             seg = float(spl[1][:-1])
         ptr = getattr(h.cas()(seg), "_ref_" + spl[0])
         self.var_mappings.update({current_uuid: ptr})
         if default_lab:
             label = spl[0]
     else:  #TODO: if not a ptr
         self.var_mappings.update({current_uuid: var})
     self.labels.update({current_uuid: label})
     logging.debug("added graph var: " + label)
     return 1
Exemple #13
0
def source_var(x, id):
    src_var(h.cas()(x), id)
Exemple #14
0
from neuron import h

a = h.Section(name='bob')
b = h.Section(name='bob')
print((a.same(b), a is b, a == b) == (False, False, False))
c = h.cas()
print((c.same(a), c == a, c.same(b), c is a, c is b) == (True, True, False,
                                                         True, False))
h('create s, d')

print((h.s.same(h.s), h.s is h.s, h.s == h.s) == (True, False, True))

print(h.s.same(5) == False)
print((h.s == 5) == False)

h('objref vv')
h('vv = new Vector(3)')
print((h.vv == h.vv, h.vv.same(h.vv)) == (False, True))
Exemple #15
0
#now only in HocTopLevelInterpreter
names = ['ref', 'cas', 'allsec', 'Section', 'setpointer']

from neuron import h
o = h
d = dir(o)
for i in names:
  assert(i in d)
  print((eval("o.%s" % i).__doc__))

o = h.IClamp()
d = dir(o)
for i in names:
  assert(i not in d)
assert('get_segment' in d)
print((o.get_segment.__doc__))

print("success")

s = [h.Section(name='s'+str(i)) for i in range(5)]
print(s)
for sec in h.allsec():
  print((h.cas()))
r = h.ref("hello")
print((r[0] == 'hello'))

Exemple #16
0
# Tutorial2.py
# Author : Jose Guzman
# Mail : jose.guzman __at__ physiologie.uni-freiburg.de

#! /usr/bin/env python

import neuron
import nrn
from neuron import h

# create soma object
soma = nrn.Section()

# soma attributes
soma.L = 30
soma.nseg = 3
soma.diam = 30

h('''
	NDEND = 2
	create soma, basal[NDEND], axon
	access basal[1]
	''')

sec = h.cas()
print (sec(), sec.name())
from neuron import h, gui
from e import e

s = h.Section()
s.insert('hh')

iname = s.hoc_internal_name()
print(iname)
exec('s2 = h.' + iname)
print('s is s2', s is s2)
print('s is h.cas()', s is h.cas())
print('s == h.cas()', s == h.cas())

h('create soma')
s4 = h.soma
print(s4.hoc_internal_name())
exec('s5 = h.' + s4.hoc_internal_name())
print('s5 is s4', s5 is s4)
print('s5 == s4', s5 == s4)
print(s5.name())
s6 = h.Section(name="s6")
s6.name()
h.topology()

h('''__nrnsec_0x { print secname() }''')
e('s7 = h.__nrnsec_0x')
h('''__nrnsec_0xaaaa { print secname() }''')
e('s7 = h.__nrnsec_0xaaaa')

del(s)
print(s2)
Exemple #18
0
def importCell(fileName, cellName, cellArgs=None, cellInstance=False):
    """
    Function for/to <short description of `netpyne.conversion.neuronPyHoc.importCell`>

    Parameters
    ----------
    fileName : <type>
        <Short description of fileName>
        **Default:** *required*

    cellName : <type>
        <Short description of cellName>
        **Default:** *required*

    cellArgs : <``None``?>
        <Short description of cellArgs>
        **Default:** ``None``
        **Options:** ``<option>`` <description of option>

    cellInstance : bool
        <Short description of cellInstance>
        **Default:** ``False``
        **Options:** ``<option>`` <description of option>

"""

    h.initnrn()

    varList = mechVarList(
    )  # list of properties for all density mechanisms and point processes
    origGlob = getGlobals(
        list(varList['mechs'].keys()) + list(varList['pointps'].keys()))
    origGlob[
        'v_init'] = -65  # add by hand since won't be set unless load h.load_file('stdrun')

    if cellArgs is None:
        cellArgs = []  # Define as empty list if not otherwise defined

    if fileName.endswith('.hoc') or fileName.endswith('.tem'):
        h.load_file(fileName)
        if not cellInstance:
            if isinstance(cellArgs, dict):
                cell = getattr(h, cellName)(
                    **cellArgs
                )  # create cell using template, passing dict with args
            else:
                cell = getattr(h, cellName)(
                    *cellArgs
                )  # create cell using template, passing list with args
        else:
            try:
                cell = getattr(h, cellName)
            except:
                cell = None
    elif fileName.endswith('.py'):
        filePath, fileNameOnly = os.path.split(
            fileName)  # split path from filename
        if filePath not in sys.path:  # add to path if not there (need to import module)
            sys.path.insert(0, filePath)
            removeFilePath = True
        else:
            removeFilePath = False
        moduleName = fileNameOnly.split('.py')[
            0]  # remove .py to obtain module name
        tempModule = importlib.import_module(moduleName)
        modulePointer = tempModule
        if isinstance(cellArgs, dict):
            cell = getattr(
                modulePointer, cellName
            )(**cellArgs)  # create cell using template, passing dict with args
        else:
            cell = getattr(modulePointer, cellName)(
                *cellArgs
            )  # create cell using template, passing list with args
        if removeFilePath: sys.path.remove(filePath)
    else:
        print("File name should be either .hoc or .py file")
        return

    secDic, secListDic, synMechs, globs = getCellParams(
        cell, varList, origGlob)

    if fileName.endswith('.py'):
        _delete_module(moduleName)
        _delete_module('tempModule')
        del modulePointer
    elif fileName.endswith('.hoc'):
        for sec in h.allsec():
            try:
                if h.cas() != sec: sec.push()
                h.delete_section()
                h.pop_section()
            except:
                pass
    h.initnrn()

    setGlobals(origGlob)  # restore original globals

    return secDic, secListDic, synMechs, globs
Exemple #19
0
from neuron import h
soma = h.Section(name='soma')
dend = h.Section(name='dend')
print(soma == h.cas())

sr = h.SectionRef()
print(soma == sr.sec)

sr = h.SectionRef(sec=dend)
print(dend == sr.sec)

sr = h.SectionRef(dend)
print(dend == sr.sec)

print(soma == h.cas())
Exemple #20
0
from neuron import h
import matplotlib.pyplot as plt
import numpy as np

h.load_file("nrngui.hoc")  # load standard run system

soma = h.Section(name='soma')
print h.cas().name(), soma.name()
soma2 = h.Section(name='soma2')
print h.cas().name(), soma2.name()

soma.insert('hh_original')
soma2.insert('hh_original')

syn = h.Exp2Syn(0.5, sec=soma2)
syn.e = 0
syn.tau1 = 1
syn.tau2 = 3

net_con = h.NetCon(soma(0.5)._ref_v, syn, 0, 5, 0.07)

stim = h.IClamp(soma(0.5))
stim.delay = 1
stim.dur = 5
stim.amp = 20

rec_cell = h.Vector()
rec_cell.record(soma(0.5)._ref_v)
rec_cell2 = h.Vector()
rec_cell2.record(soma2(0.5)._ref_v)
rec_syn = h.Vector()
Exemple #21
0
 def root_section(self):
     sref = nrn.SectionRef()
     sref.root.push()
     cas = nrn.cas()
     nrn.pop_section()
     return cas