Esempio n. 1
0
def define_biophysics(*arg):
    """Defines the biophysics of the cell, if the first argument is 1 an hh model, if 2 an adapted version of HH
     in accordance with Yu et all will be applied with following parameters:
    2st argument: cell
    3rd argument: Sodium conductance            (in S/cm^2)
    4th argument: Potassium conductance         (in S/cm^2)
    5th argument: Leak conductance              (in S/cm^2)
    6th argument: Membrane Capacitance          (in uF/cm^2)
    7th argument: Axial resistance              (in Ohm*cm)
    8th argument: Reversal potential leak       (in mV)
    9th argument: Reversal potential Sodium     (in mV)
    10th argument: Reversal potential Potassium (in mV)"""
    if arg[0] == 1:
        arg[1].insert('hh')
        arg[1].gnabar_hh = arg[2]
        arg[1].gkbar_hh = arg[3]
        arg[1].gl_hh = arg[4]
        arg[1].cm = arg[5]
        arg[1].Ra = arg[6]
        arg[1].el_hh = arg[7]
        arg[1].ena = arg[8]
        arg[1].ek = arg[9]
    if arg[0 == 2]:
        arg[1].insert('pas')
        arg[1].insert('na')
        arg[1].insert('kv')
        arg[1].gbar_na = arg[2]
        arg[1].gbar_kv = arg[3]
        arg[1].g_pas = arg[4]
        arg[1].cm = arg[5]
        arg[1].Ra = arg[6]
        arg[1].e_pas = arg[7]
        arg[1].ena = arg[8]
        arg[1].ek = arg[9]
    h.psection(sec=arg[1])
def debug():
    # Debug
    # Check section
    for sec in h.allsec():
        h.psection(sec=sec)
    # #Topology
    h.topology()
Esempio n. 3
0
 def createAxon(self, nseg=100, diam=2, L=200, Ra=123):
     '''
     Define axon biological structure.
     '''
     self.axon = h.Section(name='axon')
     self.axon.nseg = nseg
     self.axon.Ra = Ra
     self.axon.L = L
     self.axon.diam = diam
     h.psection(sec=self.axon)
Esempio n. 4
0
 def createSoma(self, cm=0.5, diam=500, L=100, Ra=35.4):
     '''
     Define soma biological structure.
     '''
     self.soma = h.Section(name='soma')
     self.soma.cm = cm
     self.soma.diam = diam
     self.soma.L = L
     self.soma.Ra = Ra
     h.psection(sec=self.soma)
Esempio n. 5
0
def one(mechname):
    m = Model(mechname)
    if 'ProbAMPANMDA_EMS' in mechname:
        m.syn.setRNG(3, 1)
    h.psection()
    dtsav = h.dt
    try:
        result = m.run()
    except:
        print("%s run failed, ignore result" % mechname)
        result = None
    h.dt = dtsav
    return m, result
Esempio n. 6
0
def main():

    tmax = 20e-3
    fs = 500e3

    sg.set_fs(fs)
    sg.set_celsius(37)

    # Acoustic stimmulation
    anf_ac = sg.ANF_Axon(record_voltages=True)

    h.topology()
    h.psection(sec=anf_ac.get_sections()[0])

    anf_ac.vesicles = [2e-3, 5e-3]

    # Electrical stimulation

    # set-up ANF
    anf_el = sg.ANF_Axon(record_voltages=True)
    # anf_el.set_geometry('straight', x0=250e-6, y0=500e-6, z0=0)
    anf_el.set_geometry('bent', a=750e-6, b=500e-6, z=0)

    # set-up electrode
    el = sg.Electrode()
    el.z = 0

    stim = np.zeros(int(tmax * fs))
    stim[int(tmax / 3 * fs):int((tmax / 3 + 1e-3) * fs)] = -0.2e-3  # (A)

    el.fs = fs
    el.stim = stim

    # `connect' ANF and electrode
    anf_el.electrodes = [el]

    # Run
    sg.run(tmax, [anf_ac, anf_el])

    # Plot
    print(anf_ac.get_spikes(), anf_el.get_spikes())

    sg.plot_vectors(anf_ac.get_voltages()[:, 0:6], fs)

    sg.plot_vectors(anf_el.get_voltages()[:, 0:6], fs)

    sg.plot_geometry([anf_el, el])

    plt.show()
Esempio n. 7
0
 def Record_Simulation_Electrical(self, T, dt=0.01):
     '''
     Run & Recording dynamics
     '''
     h.dt = dt
     h.psection()
     self.V = h.Vector()  # Membrane potential vector is created here
     self.t = h.Vector()
     self.m = h.Vector()
     self.n = h.Vector()
     self.h = h.Vector()
     self.s = h.Vector()
     self.V.record(self.soma(0.5)._ref_v)
     self.Record_Simulation_aux()
     self.t.record(h._ref_t)
     h.v_init = -60  # Let's set the initial condition of the membrane potential
     h.t = 0.0  # Let's reset the initial time of the simulation to 0 ms
     h.tstop = float(T)
     h.run()
Esempio n. 8
0
def simulatepar(delay, dur, std, offset, amp, freq, dt, tau, mu, loc, simdur,
                init, cel, seed, loop):
    init_simulation()
    cell = rn.create_cell(False)
    h.psection()
    counts = h.Vector()
    apc = h.APCount(cell.soma[0](0.5))
    apc.thresh = -15
    apc.record(counts)
    stim = attach_noise_sin_clamp(cell, delay, dur, offset, amp, freq, dt, tau,
                                  std, mu, loc, seed)
    h.dt = dt
    h.tstop = simdur
    h.v_init = init
    h.celsius = cel
    h.run()
    filename = './OUTPUT/spiketrain5Hzmfr' + str(freq) + 'freq' + str(
        std) + 'std' + str(seed) + 'seed' + str(loop) + 'loop.txt'
    writetofile(filename, counts)
    return 0
def testCell(run, plot, amplitude = 10.e-3):
    from GRANULE_Cell import Grc

    delay = 100.
    duration = 500.
    tstop = 700

    granule = Grc(position=np.zeros(3))
    electrode = h.IClamp(0.5, sec=granule.soma)
    electrode.delay = delay
    electrode.dur = duration
    electrode.amp = amplitude

    h.psection()
    h.celsius = 30
    print "Temperature of simulation is %f deg C "%h.celsius

    # run the simulation
    h.load_file("stdrun.hoc")
    h.tstop = tstop
    h.dt = 0.025
    h.steps_per_ms = 40
    h.v_init = -60

    if run:
        h.run()


        # convert the membrane potential and time values in numpy arrays
        time_points = np.array(granule.time)
        vm_points = np.array(granule.vm)

        spiking  = 0 
        threshold = 0
        spike_times = []

        for i in range(len(time_points)):

            if not spiking and vm_points[i] >= threshold:
                spike_times.append(float(time_points[i]))
                spiking = 1
            elif spiking and vm_points[i] < threshold:
                spiking = 0

        spike_times_file = open("spike_times_%sdeg_%snA.dat"%(h.celsius, electrode.amp), 'w')
        for st in spike_times:
            spike_times_file.write('%f\n'%st)
        spike_times_file.close()

        print "Saved spike times in file %s"%spike_times_file.name
        
        
        voltage_file = open("voltage_%sdeg_%snA.dat"%(h.celsius, electrode.amp), 'w')
        
        for i in range(len(time_points)):
            voltage_file.write('%s\t%s\n'%(time_points[i], vm_points[i]))
        voltage_file.close()

        print "Saved voltage in file %s"%voltage_file.name

        if plot:
            h.run()

            from matplotlib import pyplot as plt
            fig = plt.figure()
            trace_ax = fig.add_subplot(111)
            trace_ax.plot(time_points, vm_points)

            trace_ax.set_xlabel('Time (ms)')
            trace_ax.set_ylabel('mV')
            trace_ax.set_title('Membrane potential')

            fig.suptitle('Pulse duration: %d ms; pulse amplitude: %d pA; temperature: %d deg C' % (duration, amplitude * 1e3, h.celsius))

            plt.show()

    return granule
plt.plot(time_lt, rn3_lt)
plt.xlabel("time[ms]")
plt.ylabel("voltage[mV]")
twin = plt.twinx()
twin.plot(time_lt, stim_lt,'y')
twin.set_ylabel("iclamp[nA]")
twin.set_ylim(-100, 100)
TEXT = 'GPea\n'+'LENGTH = '+str(LENGTH)+' AMPLITUDE = '+str(AMPLITUDE)+' FREQUENCY = '+str(FREQUENCY)+'\nL_RATIO = ' + str(L_RATIO) + ' A_RATIO = '+str(A_RATIO)+' POLAR_T = '+str(POLAR_T)
ymin, ymax = plt.ylim()
plt.text(2,ymin+5, TEXT, fontsize = 10)
timestr = strftime("%m%d%H%M%S",localtime())
plt_filename = './graph/output'+timestr+'.png'
print plt_filename
plt.savefig(plt_filename)
plt.show()
h.psection()
"""
nframe = 0
h.cell.translation(30, 0, 0)
"""

"""
def step():
    for i in range(nstep_steprun):
        advance()

    sh.rotate(60,0,0,0,rotationPerStep,0)
    Plot()

    if 0:
        sh.printfile("temp.ps")
Esempio n. 11
0
from matplotlib import pyplot as plt
import scipy.fftpack as scfft

# Create 3 soma, one for each kind of simulation (1 clean clamp, 2 noisy)
soma = [h.Section(name='soma%d'%(i)) for i in range(3)]

v_vec = []
for s in soma: 
    # Tune the soma, inserting HH model
    s.insert('hh')
    # Change diameter, length and axial resistance
    s.L = 18.8
    s(0.5).diam = 18.8
    s.Ra = 123.
    # Some output to check the good configuration
    h.psection(sec = s)

    # Create a vector recording the membrane reversal potential during the simulation 
    v = h.Vector() 
    v.record(s(0.5)._ref_v)
    v_vec.append(v)

# Get a time vector
t_vec = h.Vector()
t_vec.record(h._ref_t)

# Configure the simulation 
res = 1000                 # Nb. of current points
min_curr = 0                # Starting stimuli current
max_curr = .4               # Max stim. current
duration = 1000             # Duration of the step
Esempio n. 12
0
import types

h("objref p")
h("p = new PythonObject()")

try:
    import pylab
    from pylab import plot, arange, figure
    my_pylab_loaded = True
except ImportError:
    print "Pylab not imported"
    my_pylab_loaded = False

def htype (obj): st=obj.hname(); sv=st.split('['); return sv[0]
def secname (obj): obj.push(); print h.secname() ; h.pop_section()
def psection (obj): obj.push(); print h.psection() ; h.pop_section()

allsecs=None #global list containing all NEURON sections, initialized via mkallsecs

# still need to generate a full allsecs
def mkallsecs ():
  """ mkallsecs - make the global allsecs variable, containing
      all the NEURON sections.
  """
  global allsecs
  allsecs=h.SectionList() # no .clear() command
  roots=h.SectionList()
  roots.allroots()
  for s in roots:
    s.push()
    allsecs.wholetree()
Esempio n. 13
0
            for i in range(sec.n3d()):
                x = sec.x3d(i)
                y = sec.y3d(i)
                c = cos(theta)
                s = sin(theta)
                xprime = x * c - y * s
                yprime = x * s + y * c
                h.pt3dchange(i,
                             xprime,
                             yprime,
                             sec.z3d(i),
                             sec.diam3d(i),
                             sec=sec)


"""
soma = h.Section(name='soma')
dend = h.Section(name='dend')

h.psection(sec=soma)
dend.connect(soma(1))
h.psection(sec=dend)
h.topology()

# Surface area of cylinder is 2*pi*r*h (sealed ends are implicit).
# Here we make a square cylinder in that the diameter
# is equal to the height, so diam = h. ==> Area = 4*pi*r^2
# We want a soma of 500 microns squared:
# r^2 = 500/(4*pi) ==> r = 6.2078, diam = 12.6157
soma.L = soma.diam = 12.6157 # Makes a soma of 500 microns squared.
dend.L = 200 # microns
Esempio n. 14
0
morph.show(2)   # show as linear schematic

# unsure how to programmatically change the size, but it is very to do in the
# gui, so just do that, and make it "whole scene" option

# translate 90 degrees over each axis
morph.rotate(0, 0, 0, 1.5708, 0, 0)     # over x axis
morph.rotate(0, 0, 0, 0, 1.5708, 0)     # over y axis
morph.rotate(0, 0, 0, 0, 0, 1.5708)     # over z axis

# save current view to file as a post script image
morph.printfile(figure_dir + 'bhalla_morphology_section.ps')

# pull out conductances as function of distance from soma or in different compartments
for sec in h.allsec():
    h.psection(sec)

for sec in h.allsec():

    if sec == h.soma:
        h.psection(sec)

    elif sec == h.axon[0]:
        h.psection(sec)

    elif sec == h.axon[5]:
        h.psection(sec)

    elif sec == h.prim_dend[4]:
        h.psection(sec)
Esempio n. 15
0
def synapse_group_test(env,
                       presyn_name,
                       gid,
                       cell,
                       syn_ids,
                       syn_mech_dict,
                       group_size,
                       v_init,
                       tstart=200.):

    syn_attrs = env.synapse_attributes

    vv = h.Vector()
    vv.append(0, 0, 0, 0, 0, 0)

    ranstream = np.random.RandomState(0)

    if len(syn_ids) == 0:
        return

    selected = ranstream.choice(np.arange(0, len(syn_ids)),
                                size=group_size,
                                replace=False)
    selected_ids = [syn_ids[i] for i in selected]

    for syn_name in syn_mech_dict:
        nclst = []

        print('synapse_group_test: %s %s synapses: %i out of %i' %
              (presyn_name, syn_name, len(selected_ids), len(syn_ids)))

        ns = h.NetStim()
        ns.interval = 1000
        ns.number = 1
        ns.start = 200
        ns.noise = 0

        nclst = []
        first_syn_id = None
        for syn_id in selected_ids:
            if syn_attrs.has_netcon(gid, syn_id, syn_name):
                syn_index = syn_attrs.syn_name_index_dict[syn_name]
                del (syn_attrs.pps_dict[gid][syn_id].netcon[syn_index])
            syn = syn_attrs.get_pps(gid, syn_id, syn_name)
            this_nc = h.NetCon(ns, syn)
            syn_attrs.add_netcon(gid, syn_id, syn_name, this_nc)
            synapses.config_syn(syn_name=syn_name,
                                rules=syn_attrs.syn_param_rules,
                                mech_names=syn_attrs.syn_mech_names,
                                nc=this_nc,
                                **syn_mech_dict[syn_name])
            nclst.append(this_nc)
            if first_syn_id is None:
                first_syn_id = syn_id
                print("%s netcon: %s" %
                      (syn_name,
                       str([
                           this_nc.weight[i]
                           for i in range(int(this_nc.wcnt()))
                       ])))

        for sec in list(cell.all):
            h.psection(sec=sec)

        v_holding_exc = -75
        v_holding_inh = -45

        if syn_name in ['NMDA', 'SatAMPA', 'AMPA']:
            v_holding = v_holding_exc
            v = cell.syntest_exc(
                tstart, v_holding, v_init,
                "MossyCell_%s_%s_synapse_trace_%i.dat" %
                (presyn_name, syn_name, group_size))
        elif syn_name in [
                'SatGABA', 'GABA', 'SatGABA_A', 'GABA_A', 'SatGABA_B', 'GABA_B'
        ]:
            v_holding = v_holding_inh
            v = cell.syntest_inh(
                tstart, v_holding, v_init,
                "MossyCell_%s_%s_synapse_trace_%i.dat" %
                (presyn_name, syn_name, group_size))
        else:
            raise RuntimeError('Unknown synapse mechanism type %s' % syn_name)
        vv = vv.add(v)

        amp = vv.x[0]
        t_10_90 = vv.x[1]
        t_20_80 = vv.x[2]
        t_all = vv.x[3]
        t_50 = vv.x[4]
        t_decay = vv.x[5]

        f = open(
            "MossyCell_%s_%s_synapse_results_%i.dat" %
            (presyn_name, syn_name, group_size), 'w')

        f.write("%s synapses: \n" % syn_name)
        f.write("  Amplitude %f\n" % amp)
        f.write("  10-90 Rise Time %f\n" % t_10_90)
        f.write("  20-80 Rise Time %f\n" % t_20_80)
        f.write("  Decay Time Constant %f\n" % t_decay)

        f.close()
## Ball and stick model w/ NEURON
## Hasan Khan
## July 28, 2016

import neuron
from neuron import h, gui
import matplotlib
from matplotlib import pyplot

## TOPOLOGY ################################################################

soma = h.Section(name='soma')
dend = h.Section(name='dend')

h.psection(
    sec=soma)  ## retrieve info using this. Pass in section u want info for

dend.connect(soma(1))  ## connects dendrite to the '1' end of the Soma

h.psection(sec=dend)

h.topology()

## GEOMETRY  ################################################################

# Surface area of cylinder is 2*pi*r*h (sealed ends are implicit).
# Here we make a square cylinder in that the diameter
# is equal to the height, so diam = h. ==> Area = 4*pi*r^2
# We want a soma of 500 microns squared:
# r^2 = 500/(4*pi) ==> r = 6.2078, diam = 12.6157
soma.L = soma.diam = 12.6157  # Makes a soma of 500 microns squared.
Esempio n. 17
0
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 14:19:18 2018

@author: janniez
"""
import numpy
from matplotlib import pyplot
from neuron import h, gui
from math import sin, cos, pi
from ballandstick import BallAndStick

cell = BallAndStick()

h.psection(sec=cell.dend)


def attach_current_clamp(cell, delay=5, dur=1, amp=.1, loc=1):
    """Attach a current Clamp to a cell.

    :param cell: Cell object to attach the current clamp.
    :param delay: Onset of the injected current.
    :param dur: Duration of the stimulus.
    :param amp: Magnitude of the current.
    :param loc: Location on the dendrite where the stimulus is placed.
    """
    stim = h.IClamp(cell.dend(loc))
    stim.delay = delay
    stim.dur = dur
    stim.amp = amp
    return stim
Esempio n. 18
0
import sys

sys.path.insert(0, "mitral_cell")
from pprint import pprint
from neuron import h
from mitralcell import MitralCell

h.nrn_load_dll("../nmodl/x86_64/.libs/libnrnmech.so")

if __name__ == "__main__":
    cell = MitralCell("1", nodes=5)

    for sec in h.allsec():
        pprint(h.psection(sec))
    print("Exited normally")
    sys.exit(1)
Esempio n. 19
0
def print_report():
    
    for sec in h.allsec():
        print h.psection()
    print h.topology()
Esempio n. 20
0
plt.ylim(-150, 150)
twin = plt.twinx()
twin.plot(time_lt, stim_lt, 'y')
twin.set_ylabel("iclamp[nA]")
twin.set_ylim(-150, 150)
TEXT = 'GPea\n' + 'LENGTH = ' + str(LENGTH) + ' AMPLITUDE = ' + str(
    AMPLITUDE) + ' FREQUENCY = ' + str(FREQUENCY) + '\nL_RATIO = ' + str(
        L_RATIO) + ' A_RATIO = ' + str(A_RATIO) + ' POLAR_T = ' + str(POLAR_T)
ymin, ymax = plt.ylim()
plt.text(2, ymin + 5, TEXT, fontsize=10)
timestr = strftime("%m%d%H%M%S", localtime())
plt_filename = './graph/output' + timestr + '.png'
print plt_filename
#plt.savefig(plt_filename,dpi=None)

print h.psection()

plt.show()
"""
nframe = 0
h.cell.translation(30, 0, 0)
"""
"""
def step():
    for i in range(nstep_steprun):
        advance()

    sh.rotate(60,0,0,0,rotationPerStep,0)
    Plot()

    if 0:
Esempio n. 21
0
10.0
>>> h.tstop
40.0
>>> h.run()
0.0
>>> plt.plot(t_vec,v_vec)
[<matplotlib.lines.Line2D object at 0x7f018e586f50>]
>>> ncstim.weight[0]=0.8
>>> plt.plot(t_vec,v_vec)
[<matplotlib.lines.Line2D object at 0x7f018e586c10>]
>>> ncstim.weight[0]=8
>>> h.run()
0.0
>>> plt.plot(t_vec,v_vec)
[<matplotlib.lines.Line2D object at 0x7f018bd1c950>]
>>> h.psection()
soma { nseg=1  L=100  Ra=35.4
	/*location 0 attached to cell 0*/
	/* First segment only */
	insert morphology { diam=500}
	insert capacitance { cm=1}
	insert pas { g_pas=0.001 e_pas=-70}
	insert AlphaSynapse { onset=1000 tau=0.1 gmax=1 e=0}
	insert ExpSyn { tau=0.1 e=0}
}
1.0
>>> ncstim.weight[0]=80
>>> h.run()
0.0
>>> plt.plot(t_vec,v_vec)
[<matplotlib.lines.Line2D object at 0x7f018ee77a10>]
        h.fcurrent()
    h.frecord_init()
    h.tstop = tstop
    h.v_init = vinit
    h.run()

def show_output(v_vec, t_vec):
    ''' show graphs 
    Parameters
    ----------
    v_vec: h.Vector()
        recorded voltage
    t_vec: h.Vector()
        recorded time
    '''
    dend_plot = pyplot.plot(t_vec, v_vec)
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mV')

if __name__ == '__main__':
    cell = cfiber(250, 0.25, 100, 0, False)
    for sec in h.allsec():
        h.psection(sec=sec) #show parameters of each section
    branch_vec, t_vec = set_recording_vectors(cell.branch)
    dend_vec, t_vec = set_recording_vectors(cell.stimsec[59])
    dend80_vec, t_vec = set_recording_vectors(cell.stimsec[20])
    simulate(cell)
    show_output(branch_vec, t_vec)
    show_output(dend_vec, t_vec)
    show_output(dend80_vec, t_vec)
    pyplot.show()
electro_tests = get_neab.substitute_parallel_for_serial(electro_tests)
tests, observation = electro_tests[0]

scores = {}
#import dask.bag as db

kl = list(izh07.type2007.keys())
E = ExternalModel()
E.inject_square_current = inject_square_current
for i in kl:
    iz07bw.reparam(type=i)
    print(iz07bw.izh.C, iz07bw.izh.k, iz07bw.izh.vr, iz07bw.izh.vt,
          iz07bw.izh.vpeak, iz07bw.izh.a, iz07bw.izh.b, iz07bw.izh.c,
          iz07bw.izh.d, iz07bw.izh.celltype)
    h.tstop = 1250
    print(h.psection())
    v = []
    recd = {'u7bw': [iz07bw.izh._ref_u], 'v7bw': [iz07bw.sec(0.5)._ref_v]}
    for x, v in recd.items():
        v.append(h.Vector(h.tstop / h.dt + 100))
        v[1].record(v[0])
    h.run()
    dt = h.dt
    print(np.shape(v[1]))
    vm = AnalogSignal(v[1], units=mV, sampling_period=dt * ms)
    E.set_membrane_potential(vm)

    for t in tests:
        score = t.judge(E)
        print(dir(E.inject_square_current))
        print(score)
Esempio n. 24
0
def synapse_group_rate_test(env,
                            presyn_name,
                            gid,
                            cell,
                            syn_ids,
                            syn_mech_dict,
                            group_size,
                            rate,
                            tstart=200.):

    syn_attrs = env.synapse_attributes

    syn_attrs = env.synapse_attributes
    ranstream = np.random.RandomState(0)

    if len(syn_ids) == 0:
        return

    selected = ranstream.choice(np.arange(0, len(syn_ids)),
                                size=group_size,
                                replace=False)
    selected_ids = [syn_ids[i] for i in selected]

    for syn_name in syn_mech_dict:

        print('synapse_group_rate_test: %s %s synapses: %i out of %i ' %
              (presyn_name, syn_name, len(selected_ids), len(syn_ids)))

        ns = h.NetStim()
        ns.interval = 1000. / rate
        ns.number = rate
        ns.start = 200
        ns.noise = 0

        nclst = []
        first_syn_id = None
        for syn_id in selected_ids:
            for syn_name in syn_mech_dict:
                if syn_attrs.has_netcon(gid, syn_id, syn_name):
                    syn_index = syn_attrs.syn_name_index_dict[syn_name]
                    del (syn_attrs.pps_dict[gid][syn_id].netcon[syn_index])
                syn = syn_attrs.get_pps(gid, syn_id, syn_name)
                this_nc = h.NetCon(ns, syn)
                syn_attrs.add_netcon(gid, syn_id, syn_name, this_nc)
                synapses.config_syn(syn_name=syn_name,
                                    rules=syn_attrs.syn_param_rules,
                                    mech_names=syn_attrs.syn_mech_names,
                                    nc=this_nc,
                                    **syn_mech_dict[syn_name])
                nclst.append(this_nc)
                if first_syn_id is None:
                    print("%s netcon: %s" %
                          (syn_name,
                           str([
                               this_nc.weight[i]
                               for i in range(int(this_nc.wcnt()))
                           ])))
            if first_syn_id is None:
                first_syn_id = syn_id

        for sec in list(cell.all):
            h.psection(sec=sec)

        print('synapse_group_rate_test: %s %s synapses: %i netcons ' %
              (presyn_name, syn_name, len(nclst)))

        v_init_exc = -75
        v_init_inh = 0

        if syn_name in ['NMDA', 'SatAMPA', 'AMPA']:
            v_init = v_init_exc
        elif syn_name in [
                'SatGABA', 'GABA', 'SatGABA_A', 'GABA_A', 'SatGABA_B', 'GABA_B'
        ]:
            v_init = v_init_inh
        else:
            raise RuntimeError('Unknown synapse mechanism type %s' % syn_name)

        res = cell.syntest_rate(tstart, rate, v_init)

        tlog = res.o(0)
        vlog = res.o(1)

        f = open(
            "MossyCell_%s_%s_synapse_rate_%i.dat" %
            (presyn_name, syn_name, group_size), 'w')

        for i in range(0, int(tlog.size())):
            f.write('%g %g\n' % (tlog.x[i], vlog.x[i]))

        f.close()
def connectcells(env, gid_list):
    datasetPath = os.path.join(env.datasetPrefix, env.datasetName)
    connectivityFilePath = os.path.join(datasetPath, env.modelConfig['Connection Data'])
    forestFilePath = os.path.join(datasetPath, env.modelConfig['Cell Data'])

    if env.verbose:
        if env.pc.id() == 0:
            print '*** Connectivity file path is %s' % connectivityFilePath

    prj_dict = defaultdict(list)
    for (src, dst) in read_projection_names(env.comm, connectivityFilePath):
        prj_dict[dst].append(src)

    if env.verbose:
        if env.pc.id() == 0:
            print '*** Reading projections: ', prj_dict.items()

    for (postsyn_name, presyn_names) in prj_dict.iteritems():

        synapse_config = env.celltypes[postsyn_name]['synapses']
        if synapse_config.has_key('spines'):
            spines = synapse_config['spines']
        else:
            spines = False

        if synapse_config.has_key('unique'):
            unique = synapse_config['unique']
        else:
            unique = False

        if synapse_config.has_key('weights'):
            has_weights = synapse_config['weights']
        else:
            has_weights = False

        if synapse_config.has_key('weights namespace'):
            weights_namespace = synapse_config['weights namespace']
        else:
            weights_namespace = 'Weights'

        if env.verbose:
            if int(env.pc.id()) == 0:
                print '*** Reading synapse attributes of population %s' % (postsyn_name)

        gid_index_synapses_map = get_cell_attributes_index_map(env.comm, forestFilePath, 'GC', 'Synapse Attributes')
        if synapse_config.has_key('weights namespace'):
            gid_index_weights_map = get_cell_attributes_index_map(env.comm, forestFilePath, 'GC', weights_namespace)
        cell_synapses_dict, cell_weights_dict = {}, {}
        for gid in gid_list:
            cell_attributes_dict = select_cell_attributes(gid, env.comm, forestFilePath, gid_index_synapses_map,
                                                              'GC', 'Synapse Attributes')
            cell_synapses_dict[gid] = {k: v for (k, v) in cell_attributes_dict['Synapse Attributes']}
            if has_weights:
                cell_attributes_dict.update(get_cell_attributes_by_gid(gid, env.comm, forestFilePath,
                                                                       gid_index_synapses_map, 'GC', weights_namespace))
                cell_weights_dict[gid] = {k: v for (k, v) in cell_attributes_dict[weights_namespace]}
                if env.verbose:
                    if env.pc.id() == 0:
                        print '*** Found synaptic weights for population %s' % (postsyn_name)
            else:
                has_weights = False
                cell_weights_dict[gid] = None
            del cell_attributes_dict

        for presyn_name in presyn_names:

            edge_count = 0

            if env.verbose:
                if env.pc.id() == 0:
                    print '*** Connecting %s -> %s' % (presyn_name, postsyn_name)

            if env.nodeRanks is None:
                (graph, a) = scatter_read_graph(env.comm, connectivityFilePath, io_size=env.IOsize,
                                                projections=[(presyn_name, postsyn_name)],
                                                namespaces=['Synapses', 'Connections'])
            else:
                (graph, a) = scatter_read_graph(env.comm, connectivityFilePath, io_size=env.IOsize,
                                                node_rank_map=env.nodeRanks,
                                                projections=[(presyn_name, postsyn_name)],
                                                namespaces=['Synapses', 'Connections'])

            edge_iter = graph[postsyn_name][presyn_name]

            connection_dict = env.connection_generator[postsyn_name][presyn_name].connection_properties
            kinetics_dict = env.connection_generator[postsyn_name][presyn_name].synapse_kinetics

            syn_id_attr_index = a[postsyn_name][presyn_name]['Synapses']['syn_id']
            distance_attr_index = a[postsyn_name][presyn_name]['Connections']['distance']

            for (postsyn_gid, edges) in edge_iter:

                postsyn_cell = env.pc.gid2cell(postsyn_gid)
                cell_syn_dict = cell_synapses_dict[postsyn_gid]

                if has_weights:
                    cell_wgt_dict = cell_weights_dict[postsyn_gid]
                    syn_wgt_dict = {int(syn_id): float(weight) for (syn_id, weight) in
                                    itertools.izip(np.nditer(cell_wgt_dict['syn_id']),
                                                   np.nditer(cell_wgt_dict['weight']))}
                else:
                    syn_wgt_dict = None

                presyn_gids = edges[0]
                edge_syn_ids = edges[1]['Synapses'][syn_id_attr_index]
                edge_dists = edges[1]['Connections'][distance_attr_index]

                cell_syn_types = cell_syn_dict['syn_types']
                cell_swc_types = cell_syn_dict['swc_types']
                cell_syn_locs = cell_syn_dict['syn_locs']
                cell_syn_sections = cell_syn_dict['syn_secs']

                edge_syn_ps_dict = synapses.mksyns(postsyn_gid,
                                                   postsyn_cell,
                                                   edge_syn_ids,
                                                   cell_syn_types,
                                                   cell_swc_types,
                                                   cell_syn_locs,
                                                   cell_syn_sections,
                                                   kinetics_dict, env,
                                                   add_synapse=synapses.add_unique_synapse if unique else synapses.add_shared_synapse,
                                                   spines=spines)

                if env.verbose:
                    if int(env.pc.id()) == 0:
                        if edge_count == 0:
                            for sec in list(postsyn_cell.all):
                                h.psection(sec=sec)

                wgt_count = 0
                for (presyn_gid, edge_syn_id, distance) in itertools.izip(presyn_gids, edge_syn_ids, edge_dists):
                    syn_ps_dict = edge_syn_ps_dict[edge_syn_id]
                    for (syn_mech, syn_ps) in syn_ps_dict.iteritems():
                        connection_syn_mech_config = connection_dict[syn_mech]
                        if has_weights and syn_wgt_dict.has_key(edge_syn_id):
                            wgt_count += 1
                            weight = float(syn_wgt_dict[edge_syn_id]) * connection_syn_mech_config['weight']
                        else:
                            weight = connection_syn_mech_config['weight']
                        delay = distance / connection_syn_mech_config['velocity']
                        if type(weight) is float:
                            h.nc_appendsyn(env.pc, h.nclist, presyn_gid, postsyn_gid, syn_ps, weight, delay)
                        else:
                            h.nc_appendsyn_wgtvector(env.pc, h.nclist, presyn_gid, postsyn_gid, syn_ps, weight, delay)
                if env.verbose:
                    if int(env.pc.id()) == 0:
                        if edge_count == 0:
                            print '*** Found %i synaptic weights for gid %i' % (wgt_count, postsyn_gid)

                edge_count += len(presyn_gids)
Esempio n. 26
0
# following this tutorial
# https://neuron.yale.edu/neuron/static/docs/neuronpython/ballandstick1.html


from neuron import h,gui
from matplotlib import pyplot
import numpy

soma = h.Section(name='soma')
dend = h.Section(name='dend')

h.psection(sec=soma)

dend.connect(soma(1))

h.psection(sec=dend)

h.topology()


# Surface area of cylinder is 2*pi*r*h (sealed ends are implicit).
# Here we make a square cylinder in that the diameter
# is equal to the height, so diam = h. ==> Area = 4*pi*r^2
# We want a soma of 500 microns squared:
# r^2 = 500/(4*pi) ==> r = 6.2078, diam = 12.6157
soma.L = soma.diam = 12.6157 # Makes a soma of 500 microns squared.
dend.L = 200 # microns
dend.diam = 1 # microns
print("Surface area of soma = {}".format(soma(0.5).area()))

#shape_window = h.PlotShape()
def mkcells(env):
    h('objref templatePaths, templatePathValue')

    rank = int(env.pc.id())
    nhosts = int(env.pc.nhost())

    v_sample_seed = int(env.modelConfig['Random Seeds']['Intracellular Voltage Sample'])
    ranstream_v_sample = np.random.RandomState()
    ranstream_v_sample.seed(v_sample_seed)

    datasetPath = os.path.join(env.datasetPrefix, env.datasetName)

    h.templatePaths = h.List()
    for path in env.templatePaths:
        h.templatePathValue = h.Value(1, path)
        h.templatePaths.append(h.templatePathValue)
    popNames = env.celltypes.keys()
    popNames.sort()
    for popName in popNames:
        templateName = env.celltypes[popName]['template']
        h.find_template(env.pc, h.templatePaths, templateName)

    dataFilePath = os.path.join(datasetPath, env.modelConfig['Cell Data'])

    if rank == 0:
        print 'cell attributes: ', env.cellAttributeInfo

    for popName in popNames:

        if env.verbose:
            if env.pc.id() == 0:
                print "*** Creating population %s" % popName

        templateName = env.celltypes[popName]['template']
        templateClass = eval('h.%s' % templateName)

        if env.celltypes[popName].has_key('synapses'):
            synapses = env.celltypes[popName]['synapses']
        else:
            synapses = {}

        v_sample_set = set([])
        env.v_dict[popName] = {}

        for gid in xrange(env.celltypes[popName]['start'],
                          env.celltypes[popName]['start'] + env.celltypes[popName]['num']):
            if ranstream_v_sample.uniform() <= env.vrecordFraction:
                v_sample_set.add(gid)

        if env.cellAttributeInfo.has_key(popName) and env.cellAttributeInfo[popName].has_key('Trees'):
            if env.verbose:
                if env.pc.id() == 0:
                    print "*** Reading trees for population %s" % popName

            if env.nodeRanks is None:
                (trees, forestSize) = scatter_read_trees(env.comm, dataFilePath, popName, io_size=env.IOsize)
            else:
                (trees, forestSize) = scatter_read_trees(env.comm, dataFilePath, popName, io_size=env.IOsize,
                                                         node_rank_map=env.nodeRanks)
            if env.verbose:
                if env.pc.id() == 0:
                    print "*** Done reading trees for population %s" % popName

            h.numCells = 0
            i = 0
            for (gid, tree) in trees:
                if env.verbose:
                    if env.pc.id() == 0:
                        print "*** Creating gid %i" % gid

                verboseflag = 0
                model_cell = cells.make_neurotree_cell(templateClass, neurotree_dict=tree, gid=gid, local_id=i,
                                                       dataset_path=datasetPath)
                if env.verbose:
                    if (rank == 0) and (i == 0):
                        for sec in list(model_cell.all):
                            h.psection(sec=sec)
                env.gidlist.append(gid)
                env.cells.append(model_cell)
                env.pc.set_gid2node(gid, int(env.pc.id()))
                ## Tell the ParallelContext that this cell is a spike source
                ## for all other hosts. NetCon is temporary.
                nc = model_cell.connect2target(h.nil)
                env.pc.cell(gid, nc, 1)
                ## Record spikes of this cell
                env.pc.spike_record(gid, env.t_vec, env.id_vec)
                ## Record voltages from a subset of cells
                if gid in v_sample_set:
                    v_vec = h.Vector()
                    soma = list(model_cell.soma)[0]
                    v_vec.record(soma(0.5)._ref_v)
                    env.v_dict[popName][gid] = v_vec
                i = i + 1
                h.numCells = h.numCells + 1
            if env.verbose:
                if env.pc.id() == 0:
                    print "*** Created %i cells" % i

        elif env.cellAttributeInfo.has_key(popName) and env.cellAttributeInfo[popName].has_key('Coordinates'):
            if env.verbose:
                if env.pc.id() == 0:
                    print "*** Reading coordinates for population %s" % popName

            if env.nodeRanks is None:
                cell_attributes_dict = scatter_read_cell_attributes(env.comm, dataFilePath, popName,
                                                                    namespaces=['Coordinates'],
                                                                    io_size=env.IOsize)
            else:
                cell_attributes_dict = scatter_read_cell_attributes(env.comm, dataFilePath, popName,
                                                                    namespaces=['Coordinates'],
                                                                    node_rank_map=env.nodeRanks,
                                                                    io_size=env.IOsize)
            if env.verbose:
                if env.pc.id() == 0:
                    print "*** Done reading coordinates for population %s" % popName

            coords = cell_attributes_dict['Coordinates']

            h.numCells = 0
            i = 0
            for (gid, _) in coords:
                if env.verbose:
                    if env.pc.id() == 0:
                        print "*** Creating gid %i" % gid

                verboseflag = 0
                model_cell = cells.make_cell(templateClass, gid=gid, local_id=i, dataset_path=datasetPath)
                env.gidlist.append(gid)
                env.cells.append(model_cell)
                env.pc.set_gid2node(gid, int(env.pc.id()))
                ## Tell the ParallelContext that this cell is a spike source
                ## for all other hosts. NetCon is temporary.
                nc = model_cell.connect2target(h.nil)
                env.pc.cell(gid, nc, 1)
                ## Record spikes of this cell
                env.pc.spike_record(gid, env.t_vec, env.id_vec)
                i = i + 1
                h.numCells = h.numCells + 1
Esempio n. 28
0
# set up the capacitance
soma.cm = 1
# μF/cm^2

# add conductances from Liu et al. 1998
soma.insert('pas')
soma.insert('na')
soma.insert('kd')

# set maximal conductances
soma(0.5).pas.g = 1 / 10000
soma(0.5).na.gbar = 1000 / 10000
soma(0.5).kd.gbar = 300 / 10000

# check to make sure everything is set up properly
h.psection(sec=soma)

# set up injected current
stim = h.IClamp(soma(0.5))
stim.amp = 0.2  # nA
stim.dur = 30000  # ms

# set up simulation
h.dt = 0.1  # ms
h.tstop = 30000  # ms

tic = time.perf_counter()  # s
h.run()
toc = time.perf_counter()  # s

# set up vectors to hold outputs
Esempio n. 29
0
 def show_all_sections(self):
     for sec in self.sections:
         h.psection(sec=sec)
Esempio n. 30
0
    # f = open('./res.txt', 'w')
    # for v in list(v_vec):
    #     f.write(str(v)+"\n")
    pyplot.legend()
    pyplot.xlabel('time (ms)')
    pyplot.ylabel('mA/cm^2')


if __name__ == '__main__':
    numofmodel = int(sys.argv[3])
    if numofmodel < 1 or numofmodel > 14:
        print("ERROR! Please input model number in range 1...14")
    else:
        cell = cfiber(250, 0.25, 0, 15020, True, numofmodel)
        for sec in h.allsec():
            h.psection(sec=sec)  #show parameters of each section
        # branch_vec, t_vec = set_recording_vectors(cell.stimsec[9])
        v_vec11, v_vec13, v_vec16, v_vec17, v_vec18, v_vecka, v_veckd, v_vec, v_veckca, t_vec = set_recording_vectors(
            cell.branch)

        vc = h.VClamp(0.5, sec=cell.stimsec[9])
        vc.dur[0] = 10.0
        vc.dur[1] = 100.0
        vc.dur[2] = 0.0
        vc.amp[0] = -55
        vc.amp[1] = -40
        vc.amp[2] = 0
        # branch_vec1, t_vec1 = set_recording_vectors(cell.stimsec[1])
        # branch_vec2, t_vec2 = set_recording_vectors(cell.stimsec[4])
        print("Number of model - ", cell.numofmodel)
        simulate(cell)
Esempio n. 31
0
from neuron import h, gui
from matplotlib import pyplot as plt

# create soma section
soma = h.Section(name='soma')
dend = h.Section(name='dend')

h.psection(soma)

# create dend section and connect to soma
dend.connect(soma(1))
h.topology()

# set geometry
soma.L = soma.diam = 12.6157  # Makes a soma of 500 microns squared.
dend.L = 200  # microns
dend.diam = 1  # microns
dend.nseg = 11

# Set membrane properties
for sec in h.allsec():
    sec.Ra = 100  # Axial resistance in Ohm * cm
    sec.cm = 1  # Membrane capacitance in micro Farads / cm^2

# Insert active Hodgkin-Huxley current in the soma
soma.insert('hh')
soma.gnabar_hh = 0.12  # Sodium conductance in S/cm2
soma.gkbar_hh = 0.036  # Potassium conductance in S/cm2
soma.gl_hh = 0.0003  # Leak conductance in S/cm2
soma.el_hh = -54.3  # Reversal potential in mV
Esempio n. 32
0
from neuron import h, gui
from neuron.units import ms, mV

soma = h.Section(name='soma')
soma.nseg = 1
soma.diam = 18.8
soma.L = 18.8
soma.Ra = 123.0
soma.insert('hh')
h.psection()

# stim
iclamp = h.IClamp(soma(0.5))
iclamp.delay = 100
iclamp.dur = 100
iclamp.amp = 0.1

# record
v = h.Vector().record(soma(0.5)._ref_v)  # Membrane potential vector
t = h.Vector().record(h._ref_t)  # Time stamp vector

# run
h.load_file('stdrun.hoc')
#h.fcurrent()                                       # Make all assigned variables (currents, conductances, etc) consistent with the values of the states. Useful in combination with finitialize().
h.finitialize(-64.97 * mV)
h.continuerun(300 * ms)

# plot
import matplotlib.pyplot as plt
plt.figure()
plt.plot(t, v)
Esempio n. 33
0
from neuron import h, gui
soma = h.Section(name='soma')
h.psection()  # prints information about the cell
#dir(soma) # shows all attributes of the cell 'soma'

dend = h.Section(name='dend')
h.psection(sec=dend)
h.topology()  # shows connection diagram

# Surface area of cylinder is 2*pi*r*h (sealed ends are implicit).
# Here we make a square cylinder in that the diameter
# is equal to the height, so diam = h. ==> Area = 4*pi*r^2
# We want a soma of 500 microns squared:
# r^2 = 500/(4*pi) ==> r = 6.2078, diam = 12.6157
soma.L = soma.diam = 12.6157  # Makes a soma of 500 microns squared.
dend.L = 180  # microns
dend.diam = 1  # microns
dend.nseg = 11  # odd number of segments

soma_area = h.area(0.5, sec=soma)
print("Surface area of soma = {}".format(soma_area, ))

# Iterate over all sections
for sec in h.allsec():
    sec.Ra = 100  # Axial resistance in Ohm * cm
    sec.cm = 1  # Membrane capacitance in micro Farads / cm^2

# Insert active Hodgkin-Huxley current in the soma
soma.insert('hh')
# Insert passive leak current in dendrite
dend.insert('pas')