Beispiel #1
0
def test_ste():

    m1 = model()
    # one state ste with two self transitions
    var = m1["s"](0.5)._ref_v
    thresh1 = h.ref(-50)
    thresh2 = h.ref(-10)
    result = []
    ste = h.StateTransitionEvent(1)
    ste.transition(0, 0, var, thresh1, (act, (1, m1, thresh1, result)))
    ste.transition(0, 0, var, thresh2, (act, (2, m1, thresh2, result)))
    fih = h.FInitializeHandler((on_finit, (ste, result)))

    run(5)
    print("final v=%g" % m1["s"](0.5).v)
    chk_result(2, result, m1)

    h.cvode_active(1)
    run(20)
    chk_result(2, result, m1)

    h.cvode_active(1)
    h.cvode.condition_order(2)
    run(5)
    chk_result(2, result, m1)

    h.cvode.condition_order(1)
    h.cvode_active(0)

    # ste associated with point process
    del fih, ste
    ste = h.StateTransitionEvent(2, m1["ic"])
    fih = h.FInitializeHandler((on_finit, (ste, result)))
    run(5)

    # transition with hoc callback
    h("""proc foo() { printf("foo called at t=%g\\n", t) }""")
    thresh3 = h.ref(-30)
    ste.transition(0, 0, var, thresh3, "foo()")
    run(5)

    # transition with hoc callback in hoc object
    h("""
begintemplate FooSTEtest
objref this
proc foo() { printf("foo in %s called at t=%g\\n", this, t) }
endtemplate FooSTEtest
""")
    thresh4 = h.ref(-20)
    obj = h.FooSTEtest()
    ste.transition(0, 0, var, thresh4, "foo()", obj)
    run(5)

    del ste, fih
    assert h.List("StateTransitionEvent").count() == 0
    assert h.List("FInitializeHandler").count() == 0
Beispiel #2
0
 def __init__(self):
     html = """
     <table style="width:100%">
         <tr><td><button data-onclick="init()">Init (mV)</button></td><td><input type="number" data-variable="v_init"></input></tr>
         <tr><td><button data-onclick="run()">Init & run</button></td></tr>
         <tr><td><button data-onclick="stopbutton()">Stop</button></td></tr>
         <tr><td><button data-onclick="do_continue_until()">Continue until (ms)</button></td><td><input type="number" data-variable="continue_til"></input></tr>
         <tr><td><button data-onclick="do_continue_for()">Continue for (ms)</button></td><td><input type="number" data-variable="continue_for"></input></tr>
         <tr><td><button data-onclick="fadvance()">Single Step</button></td></tr>
         <tr><td>t (ms)</td><td><input type="number" data-variable="t"></input></tr>
         <tr><td>tstop (ms)</td><td><input type="number" data-variable="tstop"></input></tr>
         <tr><td>dt (ms)</td><td><input type="number" data-variable="dt"></input></tr>
         <tr><td>Real Time (s)</td><td><input type="number" data-variable="realtime" disabled></input></tr>
     </table>
     """
     self.my_continue_til = h.ref(5)
     self.my_continue_for = h.ref(1)
     user_mappings = {
         'v_init':
         h._ref_v_init,
         'continue_til':
         self.my_continue_til,
         'continue_for':
         self.my_continue_for,
         't':
         h._ref_t,
         'tstop':
         h._ref_tstop,
         'dt':
         h._ref_dt,
         'run()':
         h.run,
         'init()':
         h.stdinit,
         'fadvance()':
         h.fadvance,
         'realtime':
         h._ref_realtime,
         'stopbutton()':
         self.stop,
         'do_continue_until()':
         lambda: h.continuerun(self.my_continue_til[0]),
         'do_continue_for()':
         lambda: h.continuerun(h.t + self.my_continue_for[0])
     }
     self._frame = make_browser_html(html,
                                     user_mappings=user_mappings,
                                     title='Run Control',
                                     size=(280, 400))
Beispiel #3
0
def all(substring, start=0, end=-1):
    results = []
    mt = h.MechanismType(1)
    cnt = int(mt.count())
    end = cnt if end == -1 or end > cnt else end
    for i in range(start, end):
        if mt.is_netcon_target(i) and not mt.is_artificial(i):
            mt.select(i)
            n = h.ref("")
            mt.selected(n)
            mechname = n[0]
            if substring not in mechname:
                continue
            if uses_pointer(mechname):
                print("\n%d> %s has a POINTER" % (i, mechname))
                if 'ProbAMPANMDA_EMS' not in mechname:
                    continue
            print("\n%d of %d" % (i, cnt))
            print(mechname)
            for h.secondorder in [0, 2]:
                m, result = one(mechname)
                if cnt > 30:
                    m.g = None
                if result:
                    results.append((i, result, m.g))
                del m
    h.secondorder = 0
    return results
Beispiel #4
0
def det(m):
    hm = h.Matrix(m.shape[0], m.shape[1])
    for i in range(int(hm.nrow())):
        hm.setcol(i, h.Vector(m[:, i]))
    e = h.ref(0)
    d = hm.det(e)
    return d * 10.0**e[0]
Beispiel #5
0
 def __init__ (self, type, li) :
   self.izhtype = type
   vbox, hbox, hbox1 = h.VBox(), h.HBox(), h.HBox()
   self.vbox = vbox
   lil = len(li)
   self.cols, self.rows = {20:(4,5), 8:(4,2), 9:(3,3)}[lil]
   self.label=h.ref('================================================================================')
   vbox.intercept(1)
   h.xpanel("")
   h.xvarlabel(self.label)
   if newmodel(self.izhtype):
     h.xlabel("V' = (k*(V-vr)*(V-vt) - u + Iin)/C     if (V>vpeak) V=c  [reset]")
     h.xlabel("u' = a*(b*(V-vr) - u)                  if (V>vpeak) u=u+d")
   else: 
     h.xlabel("v' = 0.04*v*v + f*v + g - u + Iin;     if (v>thresh) v=c [reset]")
     h.xlabel("u' = a*(b*v - u);                    if (v>thresh) u=u+d")
   h.xpanel()
   hbox1.intercept(1)
   h.xpanel(""); h.xbutton("RUN",h.run); h.xpanel()
   self.xvalue('I0','I0')
   self.xvalue('I1','I1')
   self.xvalue('T1','T1')
   hbox1.intercept(0); hbox1.map("")
   hbox.intercept(1)
   for ii,(k,v) in enumerate(li.iteritems()):
     if ii%self.rows==0: h.xpanel("")
     h.xbutton(k, (lambda f, arg1, arg2: lambda: f(arg1,arg2))(p, k, v)) # alternative is to use functools.partial
     if ii%self.rows==self.rows-1: h.xpanel()
   hbox.intercept(0); hbox.map("")
   vbox.intercept(0); vbox.map("Spike patterns")
   self.label[0]=""
Beispiel #6
0
def mechVarList ():
    msname = h.ref('')
    varList = {}
    for i, mechtype in enumerate(['mechs','pointps']):
        mt = h.MechanismType(i)  # either distributed mechs (0) or point process (1)
        varList[mechtype] = {}
        for j in xrange(int(mt.count())):
            mt.select(j)
            mt.selected(msname)
            ms = h.MechanismStandard(msname[0], 1) # PARAMETER (modifiable)
            varList[mechtype][msname[0]] = []
            propName = h.ref('')
            for var in xrange(int(ms.count())):
                k = ms.name(propName, var)
                varList[mechtype][msname[0]].append(propName[0])
    return varList
Beispiel #7
0
def mechVarList ():
    msname = h.ref('')
    varList = {}
    for i, mechtype in enumerate(['mechs','pointps']):
        mt = h.MechanismType(i)  # either distributed mechs (0) or point process (1)
        varList[mechtype] = {}
        for j in xrange(int(mt.count())):
            mt.select(j)
            mt.selected(msname)
            ms = h.MechanismStandard(msname[0], 1) # PARAMETER (modifiable)
            varList[mechtype][msname[0]] = []
            propName = h.ref('')
            for var in xrange(int(ms.count())):
                k = ms.name(propName, var)
                varList[mechtype][msname[0]].append(propName[0])
    return varList
Beispiel #8
0
 def paramPanel(self):
     self.box = h.VBox()
     self.box.intercept(1)
     h.xpanel('')
     h.xlabel('Likelihood numerical parameters')
     h.xlabel('    Measurement noise')
     c = self.Eve.Obs.C
     for o in c:
         h.xvalue('sigma: ' + o.hpt.s(), (o, 'sigma'), 1)
     h.xlabel('    Process noise')
     h.xvalue('Injection interval', (self, 'inj_invl'), 1,
              self.inj_invl_changed)
     s = h.Vector()
     cvodewrap.states(s)
     sref = h.ref('')
     for i in range(len(s)):
         cvodewrap.statename(i, sref, 1)
         h.xvalue('Diffusion Coeff[%d,%d]: ' % (i, i) + sref[0],
                  (self.processNoise[i], 'x'), 1, (self.fillPB, i))
     h.xcheckbox('Fox & Lu Diffusion (for Hodgkin-Huxley)?', (self, 'hhB'),
                 self.hhBButton)
     h.xvalue('  Fox & Lu: Number Na Channels', (self, 'nNa'), 1,
              self.hhBButton)
     h.xvalue('  Fox & Lu: Number K Channels', (self, 'nK'), 1,
              self.hhBButton)
     h.xlabel('    Initial Uncertainty')
     for i in range(len(s)):
         print i
         cvodewrap.statename(i, sref, 1)
         h.xvalue('Initial Stand Dev[%d]: ' % i + sref[0],
                  (self.Sdiag[i], 'x'), 1, (self.fillS, i))
     h.xbutton('Show state funnels', self.show_state_funnels)
     h.xpanel()
     self.box.intercept(0)
     self.box.map('Likelihood parameters')
Beispiel #9
0
def sparse_print(m):
    j = h.ref(0)
    for i in range(int(m.nrow())):
        print(i, end=' ')
        for jx in range(int(m.sprowlen(i))):
            x = m.spgetrowval(i, jx, j)
            print("  %d:%g" % (j[0], x))
        print()
Beispiel #10
0
def pname(msname):
    s = h.ref('')
    for i in xrange(-1, 4):
        ms = h.MechanismStandard(msname, i)
        print '\n', msname, '  vartype=%d' % i  # vartype = 1 -> PARAMETER
        for j in xrange(int(ms.count())):
            k = ms.name(s, j)
            print '%-5d %-20s size=%d' % (j, s[0], k)
Beispiel #11
0
def get_mech_globals(mechname, var=-1):
    ms = h.MechanismStandard(mechname, var)
    name = h.ref('')
    mech_globals = {}
    for j in range(ms.count()):
        ms.name(name, j)
        mech_globals[name[0]] = getattr(h, name[0])
    return mech_globals
Beispiel #12
0
def pname(msname):
    s = h.ref('')
    for i in range(-1, 4):
        ms = h.MechanismStandard(msname, i)
        print('\n', msname, '  vartype=%d' % i)  # vartype = 1 -> PARAMETER
        for j in range(int(ms.count())):
            k = ms.name(s, j)
            print('%-5d %-20s size=%d' % (j, s[0], k))
Beispiel #13
0
def cellran(gid, nclist):
    r = h.Random()
    r.Random123(gid)
    r.uniform(1.0, 1.1)
    cell = pc.gid2cell(gid)

    for sec in cell.all:
        sec.L *= r.repick()
        for seg in sec:
            seg.diam *= r.repick()
            seg.cm *= r.repick()
            #print 'diam ', seg.diam, 'cm ', seg.cm

            #mechanism variables
            for mech in seg:
                ms = h.MechanismStandard(mech.name(), 1)
                for i in range(int(ms.count())):
                    varname = h.ref("")
                    sz = ms.name(varname, i)
                    n = varname[0]
                    x = seg.__getattribute__(n)
                    setattr(seg, n, x * r.repick())
                    #print n, seg.__getattribute__(n)

            #point process parameters
            for p in seg.point_processes():
                n = p.hname()
                n = n[:n.index('[')]
                if n == 'HalfGap':
                    continue
                ms = h.MechanismStandard(n, 1)
                for i in range(int(ms.count())):
                    varname = h.ref("")
                    ms.name(varname, i)
                    x = p.__getattribute__(varname[0])
                    setattr(p, varname[0], x * r.repick())
                    #print varname[0], p.__getattribute__(varname[0])

    #netcons targeting the cell
    for nc in nclist:
        if nc.postcell() == cell:
            nc.weight[0] *= r.repick()
            nc.delay *= r.repick()

    pc.threshold(gid, pc.threshold(gid) + r.uniform(-9, 0))
Beispiel #14
0
def cellran(gid, nclist):
  r = h.Random()
  r.Random123(gid)
  r.uniform(1.0, 1.1)
  cell = pc.gid2cell(gid)

  for sec in cell.all:
    sec.L *= r.repick()
    for seg in sec:
      seg.diam *= r.repick()
      seg.cm *= r.repick()
      #print 'diam ', seg.diam, 'cm ', seg.cm

      #mechanism variables
      for mech in seg:
        ms = h.MechanismStandard(mech.name(), 1)
        for i in range(int(ms.count())):
          varname = h.ref("")
          sz = ms.name(varname, i)
          n = varname[0]
          x = seg.__getattribute__(n)
          setattr(seg, n, x * r.repick())
          #print n, seg.__getattribute__(n)

      #point process parameters
      for p in seg.point_processes():
        n = p.hname()
        n = n[:n.index('[')]
        if n == 'HalfGap':
          continue
        ms = h.MechanismStandard(n, 1)
        for i in range(int(ms.count())):
          varname = h.ref("")
          ms.name(varname, i)
          x = p.__getattribute__(varname[0])
          setattr(p, varname[0], x * r.repick())
          #print varname[0], p.__getattribute__(varname[0])
  
  #netcons targeting the cell
  for nc in nclist:
    if nc.postcell() == cell:
      nc.weight[0] *= r.repick()
      nc.delay *= r.repick()

  pc.threshold(gid, pc.threshold(gid) + r.uniform(-9, 0))
Beispiel #15
0
def ptype():
    msname = h.ref('')
    propList = {}
    for i, mechtype in enumerate(['mechs','pointps']):
        mt = h.MechanismType(i)  # either distributed mechs (0) or point process (1)
        propList[mechtype] = {}
        for j in xrange(int(mt.count())):
            mt.select(j)
            mt.selected(msname)
            print '\n\n', msname[0], ' mechanismtype=%d' % j
            pname(msname[0])
            ms = h.MechanismStandard(msname[0], 1) # PARAMETER (modifiable)
            propList[mechtype][msname[0]] = []
            propName = h.ref('')
            for prop in xrange(int(ms.count())):
                k = ms.name(propName, prop)
                propList[mechtype][msname[0]].append(propName[0])
    print propList
Beispiel #16
0
def get_mech_names():
    _mech_names = []
    mt = h.MechanismType(0)
    mname = h.ref("")
    for i in range(int(mt.count())):
        mt.select(i)
        mt.selected(mname)
        _mech_names.append(mname[0])
    return _mech_names
Beispiel #17
0
def get_mech_globals(mechname):
    ms = h.MechanismStandard(mechname, -1)
    name = h.ref('')
    mech_globals = []
    integer2 = int(ms.count())
    for j in range(integer2):
        ms.name(name, j)
        mech_globals.append(name[0])
    return mech_globals
Beispiel #18
0
def get_mech_names():
    _mech_names = []
    mt = h.MechanismType(0)
    mname = h.ref('')
    for i in range(int(mt.count())):
        mt.select(i)
        mt.selected(mname)
        _mech_names.append(mname[0])
    return _mech_names
Beispiel #19
0
def uses_pointer(mechname):
    # do not get involved with POINTER
    ms = h.MechanismStandard(mechname, 0)
    for i in range(int(ms.count())):
        n = h.ref("")
        ms.name(n, i)
        if ms.get(n[0]) == -1e+300:
            return True
    return False
Beispiel #20
0
def ptype():
    msname = h.ref('')
    propList = {}
    for i, mechtype in enumerate(['mechs', 'pointps']):
        mt = h.MechanismType(
            i)  # either distributed mechs (0) or point process (1)
        propList[mechtype] = {}
        for j in range(int(mt.count())):
            mt.select(j)
            mt.selected(msname)
            print('\n\n', msname[0], ' mechanismtype=%d' % j)
            pname(msname[0])
            ms = h.MechanismStandard(msname[0], 1)  # PARAMETER (modifiable)
            propList[mechtype][msname[0]] = []
            propName = h.ref('')
            for prop in range(int(ms.count())):
                k = ms.name(propName, prop)
                propList[mechtype][msname[0]].append(propName[0])
    print(propList)
Beispiel #21
0
def barname(mech='it'):
    '''return the name of a gbar (max conductance) for a given mechanism name'''
    l = []
    pname, ms = h.ref(''), h.MechanismStandard(mech, 1)
    for i in range(int(ms.count())):
        ms.name(pname, i)
        l.append(pname[0])
    ll = [x for x in l if 'bar' in x]
    if len(ll) != 1:
        raise Exception("Can't identify proper parameter for %s: %s" %
                        (mech, ll))
    return ll[0]
Beispiel #22
0
def get_rangevars(mech_name):
    ms = h.MechanismStandard(mech_name)
    suffix = '_' + mech_name
    lensuffix = len(suffix)
    mname = h.ref('')
    result = []
    for i in range(int(ms.count())):
        ms.name(mname, i)
        my_mname = mname[0]
        if my_mname.endswith(suffix):
            my_mname = my_mname[:-lensuffix]
        result.append({'type': 'NEURONMECH', 'mech': mech_name, 'var': my_mname, 'name': mech_name + '.' + my_mname})
    return result
Beispiel #23
0
def get_rangevars(mech_name):
    ms = h.MechanismStandard(mech_name)
    suffix = '_' + mech_name
    lensuffix = len(suffix)
    mname = h.ref('')
    result = []
    for i in range(int(ms.count())):
        ms.name(mname, i)
        my_mname = mname[0]
        if my_mname.endswith(suffix):
            my_mname = my_mname[:-lensuffix]
        result.append({'type': 'NEURONMECH', 'mech': mech_name, 'var': my_mname, 'name': mech_name + '.' + my_mname})
    return result
Beispiel #24
0
def _is_loaded_mechanisms():
    # copied from:
    # https://www.neuron.yale.edu/neuron/static/py_doc/modelspec/programmatic/mechtype.html
    mt = h.MechanismType(0)
    mname = h.ref('')
    mnames = list()
    for i in range(mt.count()):
        mt.select(i)
        mt.selected(mname)
        mnames.append(mname[0])
    if 'hh2' not in mnames:
        return False
    else:
        return True
Beispiel #25
0
def secinfo():
  result = "\n"
  for sec in h.allsec():
    r = [h.ref(0) for _ in range(3)]
    pseg = sec.parentseg()
    px = ("parent %s(%g)"%(pseg.sec.name(),pseg.x)) if pseg is not None else ""
    style = ""
    if sec.pt3dstyle():
      h.pt3dstyle(1, r[0], r[1], r[2], sec=sec)
      style = [i[0] for i in r]
    result += "%s L=%g %s %s\n" % (str(sec), sec.L, str(style), px)
    for i in range(sec.n3d()):
      result += " %d   %g %g %g %g\n" % (i, sec.x3d(i), sec.y3d(i), sec.z3d(i), sec.diam3d(i))
  return result
Beispiel #26
0
def mechVarList():
    """
    Function for/to <short description of `netpyne.conversion.neuronPyHoc.mechVarList`>


    """

    msname = h.ref('')
    varList = {}
    for i, mechtype in enumerate(['mechs', 'pointps']):
        mt = h.MechanismType(
            i)  # either distributed mechs (0) or point process (1)
        varList[mechtype] = {}
        for j in range(int(mt.count())):
            mt.select(j)
            mt.selected(msname)
            ms = h.MechanismStandard(msname[0], 1)  # PARAMETER (modifiable)
            varList[mechtype][msname[0]] = []
            propName = h.ref('')
            for var in range(int(ms.count())):
                k = ms.name(propName, var)
                varList[mechtype][msname[0]].append(propName[0])
    return varList
Beispiel #27
0
def bld(x, y):
    global g, tt, ttstr, grp, sgrp, pras
    tt = 0.0
    ttstr = h.ref('tt=0.000000000')
    v = h.VBox()
    v.intercept(1)
    g = h.Graph()
    g.size(0, x, 0, y)
    h.xpanel("", 1)
    h.xvarlabel(ttstr)
    h.xvalue("group", (this_module, "grp"), 1, ttcallback)
    h.xslider((this_module, "sgrp"), 0, 100, ttscallback)
    h.xpanel()
    v.intercept(0)
    v.map("wave front", 100, 100, 700, 500)
    return v
Beispiel #28
0
def find_template(env,
                  template_name,
                  path=['templates'],
                  template_file=None,
                  root=0):
    """
    Finds and loads a template located in a directory within the given path list.
    :param env: :class:'Env'
    :param template_name: str; name of hoc template
    :param path: list of str; directories to look for hoc template
    :param template_file: str; file_name containing definition of hoc template
    :param root: int; MPI.COMM_WORLD.rank
    """
    pc = env.pc
    rank = int(pc.id())
    found = False
    foundv = h.Vector(1)
    template_path = ''
    if template_file is None:
        template_file = '%s.hoc' % template_name
    if pc is not None:
        pc.barrier()
    if (pc is None) or (int(pc.id()) == root):
        for template_dir in path:
            if template_file is None:
                template_path = '%s/%s.hoc' % (template_dir, template_name)
            else:
                template_path = '%s/%s' % (template_dir, template_file)
            found = os.path.isfile(template_path)
            if found and (rank == root):
                logger.info('Loaded %s from %s' %
                            (template_name, template_path))
                break
        foundv.x[0] = 1 if found else 0
    if pc is not None:
        pc.barrier()
        pc.broadcast(foundv, root)
    if foundv.x[0] > 0.0:
        s = h.ref(template_path)
        if pc is not None:
            pc.broadcast(s, root)
        h.load_file(s)
    else:
        raise Exception(
            'find_template: template %s not found: file %s; path is %s' %
            (template_name, template_file, str(path)))
Beispiel #29
0
def get_rangevars(mech_name):
    ms = h.MechanismStandard(mech_name)
    suffix = "_" + mech_name
    lensuffix = len(suffix)
    mname = h.ref("")
    result = []
    for i in range(int(ms.count())):
        ms.name(mname, i)
        my_mname = mname[0]
        if my_mname.endswith(suffix):
            my_mname = my_mname[:-lensuffix]
        result.append({
            "type": "NEURONMECH",
            "mech": mech_name,
            "var": my_mname,
            "name": mech_name + "." + my_mname,
        })
    return result
Beispiel #30
0
def is_loaded_mechanisms():
    # copied from:
    # https://www.neuron.yale.edu/neuron/static/py_doc/modelspec/programmatic/mechtype.html
    mt = h.MechanismType(0)
    mname = h.ref('')
    mnames = list()
    for i in range(mt.count()):
        mt.select(i)
        mt.selected(mname)
        mnames.append(mname[0])

    # note this check only works for the original hnn model
    # need to generalize for any model

    if 'hh2' not in mnames:
        return False
    else:
        return True
Beispiel #31
0
 def constraintsPanel(self):
     self.box = h.HBox()
     self.box.intercept(1)
     self.box.ref(self)
     s = h.Vector()
     cvodewrap.states(s)
     nstates = len(s)
     sref = h.ref('')
     h.xpanel("")
     h.xlabel('0<=')
     for i in range(nstates):
         h.xcheckbox('', (self.geq0[i], 'x'), self.constraintsButton)
     h.xpanel()
     h.xpanel("")
     h.xlabel('>=1')
     for i in range(nstates):
         cvodewrap.statename(i, sref, 1)
         h.xcheckbox(sref[0], (self.leq1[i], 'x'), self.constraintsButton)
     h.xpanel()
     for j in range(self.nsums):
         h.xpanel("")
         h.xlabel("S%d" % j)
         for i in range(nstates):
             h.xcheckbox('', (self.sumto1[j][i], 'x'),
                         self.constraintsButton)
         h.xpanel()
     h.xpanel("")
     h.xbutton("Add Sum-to-1", self.constraintsButton)
     h.xbutton("Remove Empty", self.constraintsButton)
     h.xbutton("Close", self.constraintsButton)
     h.xlabel('QP Solver:')
     h.xstatebutton('cvxopt', (self, 'cvxopt_sel'), self.constraintsButton)
     h.xstatebutton('custom', (self, 'custom_sel'), self.constraintsButton)
     h.xpanel()
     self.box.intercept(0)
     self.box.map("Constraints")
Beispiel #32
0
from neuron import h

h.load_file('stdrun.hoc')

soma = h.Section(name='soma')
seg = soma(0.5)
soma.insert('hh')

ic = h.IClamp(seg)
ic.amp = 40  # since by default a very large section
ic.delay = 1
ic.dur = 1

is_checked_ref = h.ref(0)


class Ref():
    def __init__(self, checked):
        self.checked = checked


is_checked = Ref(0)


def onpress():
    print("checkbox changed! as if")
    if isinstance(is_checked, Ref):
        print("value: ", is_checked.checked)
    else:
        print("value: ", is_checked[0])
    return
Beispiel #33
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'))

Beispiel #34
0
from neuron import h
# Print the names of all density mechanisms
mt = h.MechanismType(0)
mname  = h.ref('')
integer = int(mt.count())
print(type(integer))
for i in range(integer):
    mt.select(i)
    mt.selected(mname)
    print(mname[0])

def get_mech_globals(mechname):
    ms = h.MechanismStandard(mechname, -1)
    name = h.ref('')
    mech_globals = []
    integer2 = int(ms.count())
    for j in range(integer2):
        ms.name(name, j)
        mech_globals.append(name[0])
    return mech_globals

print(get_mech_globals('ca_ion'))
Beispiel #35
0
def psection(sec):
    from neuron import h, _has_rxd
    try:
        if _has_rxd['crxd']:
            from neuron import crxd as rxd
            from neuron.crxd import region, species
            from neuron.crxd import rxd as rxd_module

        else:
            from neuron import rxd
            from neuron.rxd import region, species
            from neuron.rxd import rxd as rxd_module
        have_rxd = True
    except:
      have_rxd = False

    results = {}

    mname = h.ref('')

    # point processes
    pps = {}
    mt = h.MechanismType(1)
    for i in range(int(mt.count())):
        mt.select(i)
        mypps = set()
        pp = mt.pp_begin(sec=sec)
        while pp is not None:
            mypps.add(pp)
            pp = mt.pp_next()
        if mypps:
            mt.selected(mname)
            pps[mname[0]] = mypps
    results['point_processes'] = pps


    center_seg_dir = dir(sec(0.5))

    mechs_present = []

    # membrane mechanisms
    mt = h.MechanismType(0)

    for i in range(int(mt.count())):
        mt.select(i)
        mt.selected(mname)
        name = mname[0]
        if name in center_seg_dir:
            mechs_present.append(name)

    results['density_mechs'] = {}
    results['ions'] = {}

    for mech in mechs_present:
        my_results = {}
        ms = h.MechanismStandard(mech, 0)
        for j in range(int(ms.count())):
            n = int(ms.name(mname, j))
            name = mname[0]
            pvals = []
            # TODO: technically this is assuming everything that ends with _ion
            #       is an ion. Check this.
            if mech.endswith('_ion'):
                pvals = [getattr(seg, name) for seg in sec]
            else:
                mechname = name#+ '_' + mech
                for seg in sec:
                    if n > 1:
                        pvals.append([getattr(seg, mechname)[i] for i in range(n)])
                    else:
                        pvals.append(getattr(seg, mechname))
            my_results[name[:-(len(mech) + 1)] if name.endswith('_' + mech) else name] = pvals
        # TODO: should be a better way of testing if an ion
        if mech.endswith('_ion'):
            results['ions'][mech[:-4]] = my_results
        else:
            results['density_mechs'][mech] = my_results

    morphology = {'L': sec.L,
                  'diam': [seg.diam for seg in sec],
                  'pts3d': [(sec.x3d(i), sec.y3d(i), sec.z3d(i), sec.diam3d(i)) for i in range(sec.n3d())],
                  'parent': sec.parentseg(),
                  'trueparent': sec.trueparentseg()}

    results['morphology'] = morphology
    results['nseg'] = sec.nseg
    results['Ra'] = sec.Ra
    results['cm'] = [seg.cm for seg in sec]

    if have_rxd:
        regions = {r() for r in region._all_regions if r() is not None and sec in r().secs}
        results['regions'] = regions

        my_species = []
        for sp in species._all_species:
            sp = sp()
            if sp is not None:
                sp_regions = sp._regions
                if not hasattr(sp_regions, '__len__'):
                    sp_regions = [sp_regions]
                if any(r in sp_regions for r in regions):
                    my_species.append(sp)
        results['species'] = set(my_species)
        results['name'] = sec.hname()
        results['hoc_internal_name'] = sec.hoc_internal_name()
        results['cell'] = sec.cell()

        #all_active_reactions = [r() for r in rxd_module._all_reactions if r() is not None]

    return results
Beispiel #36
0
def psection(sec):
    from neuron import h, _has_rxd
    try:
        if _has_rxd['crxd']:
            from neuron import crxd as rxd
            from neuron.crxd import region, species
            from neuron.crxd import rxd as rxd_module

        else:
            from neuron import rxd
            from neuron.rxd import region, species
            from neuron.rxd import rxd as rxd_module
        have_rxd = True
    except:
        have_rxd = False

    results = {}

    mname = h.ref('')

    # point processes
    pps = {}
    mt = h.MechanismType(1)
    for i in range(int(mt.count())):
        mt.select(i)
        mypps = set()
        pp = mt.pp_begin(sec=sec)
        while pp is not None:
            mypps.add(pp)
            pp = mt.pp_next()
        if mypps:
            mt.selected(mname)
            pps[mname[0]] = mypps
    results['point_processes'] = pps

    center_seg_dir = dir(sec(0.5))

    mechs_present = []

    # membrane mechanisms
    mt = h.MechanismType(0)

    for i in range(int(mt.count())):
        mt.select(i)
        mt.selected(mname)
        name = mname[0]
        if name in center_seg_dir:
            mechs_present.append(name)

    results['density_mechs'] = {}
    results['ions'] = {}

    for mech in mechs_present:
        my_results = {}
        ms = h.MechanismStandard(mech, 0)
        for j in range(int(ms.count())):
            n = int(ms.name(mname, j))
            name = mname[0]
            pvals = []
            # TODO: technically this is assuming everything that ends with _ion
            #       is an ion. Check this.
            if mech.endswith('_ion'):
                pvals = [getattr(seg, name) for seg in sec]
            else:
                mechname = name  #+ '_' + mech
                for seg in sec:
                    if n > 1:
                        pvals.append(
                            [getattr(seg, mechname)[i] for i in range(n)])
                    else:
                        pvals.append(getattr(seg, mechname))
            my_results[name[:-(len(mech) +
                               1)] if name.endswith('_' +
                                                    mech) else name] = pvals
        # TODO: should be a better way of testing if an ion
        if mech.endswith('_ion'):
            results['ions'][mech[:-4]] = my_results
        else:
            results['density_mechs'][mech] = my_results

    morphology = {
        'L':
        sec.L,
        'diam': [seg.diam for seg in sec],
        'pts3d': [(sec.x3d(i), sec.y3d(i), sec.z3d(i), sec.diam3d(i))
                  for i in range(sec.n3d())],
        'parent':
        sec.parentseg(),
        'trueparent':
        sec.trueparentseg()
    }

    results['morphology'] = morphology
    results['nseg'] = sec.nseg
    results['Ra'] = sec.Ra
    results['cm'] = [seg.cm for seg in sec]

    if have_rxd:
        regions = {
            r()
            for r in region._all_regions if r() is not None and sec in r().secs
        }
        results['regions'] = regions

        my_species = []
        for sp in species._all_species:
            sp = sp()
            if sp is not None:
                sp_regions = sp._regions
                if not hasattr(sp_regions, '__len__'):
                    sp_regions = [sp_regions]
                if any(r in sp_regions for r in regions):
                    my_species.append(sp)
        results['species'] = set(my_species)
        results['name'] = sec.hname()
        results['hoc_internal_name'] = sec.hoc_internal_name()
        results['cell'] = sec.cell()

        #all_active_reactions = [r() for r in rxd_module._all_reactions if r() is not None]

    return results
Beispiel #37
0
from neuron import h
for j in range(2):
    mt = h.MechanismType(j)
    name = h.ref("")
    for i in range(mt.count()):
        mt.select(i)
        mt.selected(name)
        a = mt.code().split(sep='\n')
        print(("%s : %s" % (name[0], a[0])))
Beispiel #38
0
 def all_mechanism_types():
     """Return a dictionary of all available mechanism types.
     
     Each dictionary key is the name of a mechanism and each value is
     another dictionary containing information about the mechanism::
     
         mechanism_types = {
             'mech_name1': {
                 'point_process': bool,
                 'artificial_cell': bool,
                 'netcon_target': bool,
                 'has_netevent': bool,
                 'internal_type': int,
                 'globals': {name:size, ...},
                 'parameters': {name:size, ...},
                 'assigned': {name:size, ...},
                 'state': {name:size, ...},
             },
             'mech_name2': {...},
             'mech_name3': {...},
             ...
         }
     
     * point_process: False for distributed mechanisms, True for point 
       processes and artificial cells.
     * artificial_cell: True for artificial cells, False otherwise
     * netcon_target: True if the mechanism can receive NetCon events
     * has_netevent: True if the mechanism can emit NetCon events
     * internal_type: Integer specifying the NEURON internal type index of 
       the mechanism
     * globals: dict of the name and vector size of the mechanism's global
       variables
     * parameters: dict of the name and vector size of the mechanism's 
       parameter variables
     * assigned: dict of the name and vector size of the mechanism's 
       assigned variables
     * state: dict of the name and vector size of the mechanism's state
       variables
       
     For more information on global, parameter, assigned, and state 
     variables see:
     http://www.neuron.yale.edu/neuron/static/docs/help/neuron/nmodl/nmodl.html
     """
     if Mechanism._mech_types is None:
         Mechanism._mech_types = collections.OrderedDict()
         mname = h.ref('')
         # Iterate over two mechanism types (distributed, point/artificial)
         for i in [0, 1]:
             mt = h.MechanismType(i)
             nmech = int(mt.count())
             # Iterate over all mechanisms of this type
             for j in range(nmech):
                 mt.select(j)
                 mt.selected(mname)
                 
                 # General mechanism properties
                 name = mname[0]  # convert hoc string ptr to python str
                 
                 desc = {
                     'point_process': bool(i),
                     'netcon_target': bool(mt.is_netcon_target(j)),
                     'has_netevent': bool(mt.has_net_event(j)),
                     'artificial_cell': bool(mt.is_artificial(j)),
                     'internal_type': int(mt.internal_type()),
                 }
                 
                 # Collect information about 4 different types of variables
                 for k,ptype in [(-1, 'globals'), (1, 'parameters'), 
                                 (2, 'assigned'), (3, 'state')]:
                     desc[ptype] = {} # collections.OrderedDict()
                     ms = h.MechanismStandard(name, k)
                     for l in range(int(ms.count())):
                         psize = ms.name(mname, l)
                         pname = mname[0]  # parameter name
                         desc[ptype][pname] = int(psize)
                 
                 # Assemble everything in one place
                 Mechanism._mech_types[name] = desc
             
     return Mechanism._mech_types