forked from soltesz-lab/dentate
/
neuron_utils.py
324 lines (283 loc) · 10.4 KB
/
neuron_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import os, os.path
try:
from mpi4py import MPI # Must come before importing NEURON
except Exception:
pass
from dentate.utils import *
from neuron import h
from scipy import interpolate
# This logger will inherit its settings from the root logger, created in dentate.env
logger = get_module_logger(__name__)
freq = 100 # Hz, frequency at which AC length constant will be computed
d_lambda = 0.1 # no segment will be longer than this fraction of the AC length constant
default_ordered_sec_types = ['soma', 'hillock', 'ais', 'axon', 'basal', 'trunk', 'apical', 'tuft', 'spine_neck',
'spine_head']
default_hoc_sec_lists = {'soma': 'somaidx', 'hillock': 'hilidx', 'ais': 'aisidx', 'axon': 'axonidx',
'basal': 'basalidx', 'apical': 'apicalidx', 'trunk': 'trunkidx', 'tuft': 'tuftidx'}
IzhiCellAttrs = namedtuple('IzhiCellAttrs', ['C', 'k', 'vr', 'vt', 'vpeak', 'a', 'b', 'c', 'd', 'celltype'])
default_izhi_cell_attrs_dict = {
'RS': IzhiCellAttrs(C=1., k=0.7, vr=-65., vt=-50., vpeak=35., a=0.03, b=-2., c=-55., d=100., celltype=1),
'IB': IzhiCellAttrs(C=1.5, k=1.2, vr=-75., vt=-45., vpeak=50., a=0.01, b=5., c=-56., d=130., celltype=2),
'CH': IzhiCellAttrs(C=0.5, k=1.5, vr=-60., vt=-40., vpeak=25., a=0.03, b=1., c=-40., d=150., celltype=3),
'LTS': IzhiCellAttrs(C=1.0, k=1.0, vr=-56., vt=-42., vpeak=40., a=0.03, b=8., c=-53., d=20., celltype=4),
'FS': IzhiCellAttrs(C=0.2, k=1., vr=-55., vt=-40., vpeak=25., a=0.2, b=-2., c=-45., d=-55., celltype=5),
'TC': IzhiCellAttrs(C=2.0, k=1.6, vr=-60., vt=-50., vpeak=35., a=0.01, b=15., c=-60., d=10., celltype=6),
'RTN': IzhiCellAttrs(C=0.4, k=0.25, vr=-65., vt=-45., vpeak=0., a=0.015, b=10., c=-55., d=50., celltype=7)
}
def hoc_results_to_python(hoc_results):
results_dict = {}
for i in range(0, int(hoc_results.count())):
vect = hoc_results.o(i)
gid = int(vect.x[0])
pyvect = vect.to_python()
results_dict[gid] = pyvect[1:]
hoc_results.remove_all()
return results_dict
def simulate(v_init, mainlength, prelength=0, cvode=True):
"""
:param h:
:param v_init:
:param prelength:
:param mainlength:
:param cvode:
"""
h.cvode_active(1 if cvode else 0)
h.finitialize(v_init)
h.tstop = prelength + mainlength
h.fadvance()
h.continuerun(h.tstop)
def mknetcon(pc, source, syn, weight=1, delay=0.1):
"""
Creates a network connection from the provided source to the provided synaptic point process.
:param pc: :class:'h.ParallelContext'
:param source: int; source gid
:param syn: synapse point process
:param delay: float
:param weight: float
:return: :class:'h.NetCon'
"""
nc = pc.gid_connect(source, syn)
nc.weight[0] = weight
nc.delay = delay
return nc
def mknetcon_vecstim(syn, delay=0.1, weight=1, source=None):
"""
Creates a VecStim object to drive the provided synaptic point process,
and a network connection from the VecStim source to the synapse target.
:param syn: synapse point process
:param delay: float
:param weight: float
:return: :class:'h.NetCon', :class:'h.VecStim'
"""
vs = h.VecStim()
nc = h.NetCon(vs, syn)
nc.weight[0] = weight
nc.delay = delay
return nc, vs
def mkgap(env, cell, gid, secpos, secidx, sgid, dgid, w):
"""
Create gap junctions
:param pc:
:param gjlist:
:param gid:
:param secidx:
:param sgid:
:param dgid:
:param w:
:return:
"""
sec = list(cell.sections)[secidx]
seg = sec(secpos)
gj = h.ggap(seg)
gj.g = w
env.pc.source_var(seg._ref_v, sgid, sec=sec)
env.pc.target_var(gj, gj._ref_vgap, dgid)
env.gjlist.append(gj)
return gj
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)))
def configure_hoc_env(env):
"""
:param env: :class:'Env'
"""
h.load_file("stdrun.hoc")
h.load_file("loadbal.hoc")
for template_dir in env.template_paths:
path = "%s/rn.hoc" % template_dir
if os.path.exists(path):
h.load_file(path)
h('objref pc, nc, nil')
h('strdef dataset_path')
if hasattr(env, 'dataset_path'):
h.dataset_path = env.dataset_path if env.dataset_path is not None else ""
h.pc = h.ParallelContext()
h.pc.gid_clear()
env.pc = h.pc
h.dt = env.dt
h.tstop = env.tstop
env.t_vec = h.Vector() # Spike time of all cells on this host
env.id_vec = h.Vector() # Ids of spike times on this host
env.t_rec = h.Vector() # Timestamps of intracellular traces on this host
if 'celsius' in env.globals:
h.celsius = env.globals['celsius']
## more accurate integration of synaptic discontinuities
if hasattr(h, 'nrn_netrec_state_adjust'):
h.nrn_netrec_state_adjust = 1
## sparse parallel transfer
if hasattr(h, 'nrn_sparse_partrans'):
h.nrn_sparse_partrans = 1
find_template(env, 'StimCell', path=env.template_paths)
find_template(env, 'VecStimCell', path=env.template_paths)
def load_cell_template(env, pop_name):
"""
:param pop_name: str
"""
if pop_name in env.template_dict:
return env.template_dict[pop_name]
rank = env.comm.Get_rank()
if not (pop_name in env.celltypes):
raise KeyError('load_cell_templates: unrecognized cell population: %s' % pop_name)
template_name = env.celltypes[pop_name]['template']
if 'template file' in env.celltypes[pop_name]:
template_file = env.celltypes[pop_name]['template file']
else:
template_file = None
if not hasattr(h, template_name):
find_template(env, template_name, template_file=template_file, path=env.template_paths)
assert (hasattr(h, template_name))
template_class = getattr(h, template_name)
env.template_dict[pop_name] = template_class
return template_class
def make_rec(recid, population, gid, cell, sec=None, loc=None, ps=None, param='v', label=None, dt=h.dt, description=''):
"""
Makes a recording vector for the specified quantity in the specified section and location.
:param recid: str
:param population: str
:param gid: integer
:param cell: :class:'BiophysCell'
:param sec: :class:'HocObject'
:param loc: float
:param ps: :class:'HocObject'
:param param: str
:param dt: float
:param ylabel: str
:param description: str
"""
vec = h.Vector()
if (sec is None) and (loc is None) and (ps is not None):
hocobj = ps
seg = ps.get_segment()
if seg is not None:
loc = seg.x
sec = seg.sec
origin = list(cell.soma)[0]
distance = h.distance(origin(0.5), seg)
else:
distance = None
elif (sec is not None) and (loc is not None):
hocobj = sec(loc)
origin = list(cell.soma)[0]
h.distance(sec=origin)
distance = h.distance(loc, sec=sec)
else:
raise RuntimeError('make_rec: either sec and loc or ps must be specified')
section_index = None
if sec is not None:
for i, this_section in enumerate(cell.sections):
if this_section == sec:
section_index = i
break
if label is None:
label = param
vec.record(getattr(hocobj, '_ref_%s' % param), dt)
rec_dict = {'name': recid,
'gid': gid,
'cell': cell,
'population': population,
'loc': loc,
'section': section_index,
'distance': distance,
'description': description,
'vec': vec,
'label': label
}
return rec_dict
# Code by Michael Hines from this discussion thread:
# https://www.neuron.yale.edu/phpBB/viewtopic.php?f=31&t=3628
def cx(env):
"""
Estimates cell complexity. Uses the LoadBalance class.
:param env: an instance of the `dentate.Env` class.
"""
rank = int(env.pc.id())
lb = h.LoadBalance()
if os.path.isfile("mcomplex.dat"):
lb.read_mcomplex()
cxvec = h.Vector(len(env.gidset))
for i, gid in enumerate(env.gidset):
cxvec.x[i] = lb.cell_complexity(env.pc.gid2cell(gid))
env.cxvec = cxvec
return cxvec
def interplocs(sec, locs):
"""Computes xyz coords of locations in a section whose topology & geometry are defined by pt3d data.
Based on code by Ted Carnevale.
"""
nn = sec.n3d()
xx = h.Vector(nn)
yy = h.Vector(nn)
zz = h.Vector(nn)
ll = h.Vector(nn)
for ii in range(0, nn):
xx.x[ii] = sec.x3d(ii)
yy.x[ii] = sec.y3d(ii)
zz.x[ii] = sec.z3d(ii)
ll.x[ii] = sec.arc3d(ii)
## normalize length
ll.div(ll.x[nn - 1])
xx = xx.to_python()
yy = yy.to_python()
zz = zz.to_python()
ll = ll.to_python()
pch_x = interpolate.pchip(ll, xx)
pch_y = interpolate.pchip(ll, yy)
pch_z = interpolate.pchip(ll, zz)
res = np.asarray([(pch_x(loc), pch_y(loc), pch_z(loc)) for loc in locs], dtype=np.float32)
return res