Using Python as NEURON's interpreter

Getting Started

From a terminal window, launch with
nrniv -python
To gain access to the HOC interpreter, use
from neuron import h
Everything you could do in HOC you can do through the h object.
#execute a hoc statement
h('printf("hello world\\n")') #but note how we had to escape the backslash

#create a hoc Object and execute its methods
v = h.Vector(5)
v.indgen() # parentheses are not optional
v.printf()
v.x[2]
for x in v:
  print x

#create sections, etc.
soma = h.Section()
axon = h.Section()
axon.connect(soma, 1)
axon.nseg = 3
h.topology() # sadly, they are anonymous in the hoc world

for sec in h.allsec():
  sec.insert('hh')

axon.gnabar_hh = .1      # for whole section must use old hoc rangevar name
axon(.5).hh.gnabar = .09 # for a segment, can use either
for sec in h.allsec():
  for seg in sec:
    print sec, seg.x, seg.hh.gnabar
    
See the Python Accessing HOC documentation for further information.

Going further

Some hoc functions use callbacks.
from neuron import h
h.load_file('nrngui.hoc')

def callback1():
        print "callback1: t=%s" % h.t
        interval = 10000
        print "next callback1 at %s" % (h.t+interval)
        h.cvode.event(h.t + interval, callback1)

h.cvode_active(1)
fih = h.FInitializeHandler(callback1)
h.stdinit()
h.cvode.solve(50000)
Some hoc functions use pointers to HOC variables.
from neuron import h
h.load_file('nrngui.hoc')

soma = h.Section()
soma.L = 10
soma.diam = 10
soma.insert('hh')
stim = h.IClamp(.5, sec=soma)
stim.delay = .1
stim.dur = .1
stim.amp = .3

vvec = h.Vector()
vvec.record(soma(.5)._ref_v, sec=soma)
tvec = h.Vector()
tvec.record(h._ref_t, sec=soma)

h.run()
g = h.Graph()
g.size(0,5,-80,40)
vvec.line(g, tvec)


NEURON hands-on course
Copyright © 1998-2010 by N.T. Carnevale and M.L. Hines, all rights reserved.