Ejemplo n.º 1
0
    def draw(self):
        """ Draw a visual representation of the optrode """
        from neuron import gui
        if not hasattr(self,'gOpt'):
            from numpy import pi
            self.gOpt=h.Shape(0)
            self.gOpt.view(-2100, -2100, 4200, 4200, 230, 450, 200.64, 200.32)
            self.gOpt.rotate(0, 0, 0, pi/2, 0, 0)
        h.pt3dclear(sec = self.sec)
        h.pt3dadd(self.x[0],
                  self.y[0],
                  self.z[0],
                  self.diameter,
                  sec = self.sec)
        h.pt3dadd(self.x[1],
                  self.y[1],
                  self.z[1],
                  self.diameter,
                  sec = self.sec)
        self.pOpt0 = h.IClamp(0,
                              sec = self.sec)
        self.pOpt1 = h.IClamp(1,
                              sec = self.sec)

        self.gOpt.point_mark(self.pOpt0, 1)  # make start black
        self.gOpt.point_mark(self.pOpt1, 3)  # make output blue
        self.gOpt.exec_menu("Show Diam")
        self.gOpt.exec_menu("3D Rotate")
Ejemplo n.º 2
0
 def __init__(self, pts, master=True):
     self.master = master
     diam = p.cell_diameter
     self.pts = pts
     self.sections = {}
     self.sl = h.SectionList()
     for pt in pts:
         gid = org2gid(*pt)
         sec = h.Section(name=str(gid))
         sec.pt3dclear()
         #draw the line a little shorter so we can see the junctions
         p1 = xyz(*pt)
         p2 = xyz(pt[0], pt[1], pt[2] + 1)
         dp = (p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2])
         x, y, z = p1[0] + .05 * dp[0], p1[1] + .05 * dp[1], p1[
             2] + .05 * dp[2]
         sec.pt3dadd(x, y, z, diam - 1)
         x, y, z = p2[0] - .05 * dp[0], p2[1] - .05 * dp[1], p2[
             2] - .05 * dp[2]
         sec.pt3dadd(x, y, z, diam - 1)
         self.sections[sec] = gid
         self.sl.append(sec=sec)
     self.sh = h.Shape(self.sl)
     self.sh.menu_tool("print info", self.callback)
     if not master:
         for sec in self.sections:
             self.sh.color(gid2org(self.sections[sec])[0] + 1, sec=sec)
Ejemplo n.º 3
0
    def show_synapses_PP_LTP(self):
        """Shows a box containing the model shape plot with marked recording sites and synapses."""
        # build dummy current clamps and demarcate locations
        dum_CC = [
            h.IClamp(self.CA1.lm_medium1(0.1)),
            h.IClamp(self.CA1.radTdist2(0.1))
        ]
        for cc in dum_CC:
            cc.dur = 0
            cc.amp = 0

        self.vBoxShape = h.VBox()
        self.vBoxShape.intercept(True)
        self.shplot = h.Shape()

        for sec in self.synapses:
            for syn in self.synapses[sec]:
                if syn.type == 'AMPA':
                    self.shplot.point_mark(syn.synapse, 1, 'O', 6)

        self.shplot.point_mark(dum_CC[0], 2, 'O', 12)
        self.shplot.point_mark(dum_CC[1], 3, 'O', 12)

        self.shplot.label("Large circles: recording sites")
        self.shplot.label("Black: Synapses")
        self.shplot.exec_menu("Whole Scene")
        self.shplot.flush()
        self.vBoxShape.intercept(0)
        self.vBoxShape.map("Spatial distribution of point processes", 1200, 0,
                           500, 900)
        self.shplot.exec_menu("View = plot")
        self.shplot.exec_menu("Show Diam")
Ejemplo n.º 4
0
Archivo: Fig4.py Proyecto: torbjone/EEG
def present_synapses(SynList, c=2, STYLE=4, SIZE=8):
    shp = h.Shape()
    shp.rotate(0, 0, 0, 0, 0, 5.25)

    shp.show(0)
    for syn in SynList:
        shp.point_mark(syn, c, STYLE, SIZE)

    shp.view(-322, -600, 620, 1500, 800, 0, 800, 1800)
Ejemplo n.º 5
0
def present_synapses(SynList, c=2, STYLE=4, SIZE=8):
    shp_list.append(h.Shape())
    shp_list[-1].rotate(0, 0, 0, 0, 0, 5.25)

    shp_list[-1].show(0)
    for syn in SynList:
        shp_list[-1].point_mark(syn, c, STYLE, SIZE)

    shp_list[-1].view(-322, -600, 620, 1500, 0 + 100 * len(shp_list), 0, 200,
                      450)
Ejemplo n.º 6
0
table_dir = project_dir + 'analysis/tables/'
noise_dir = project_dir + 'scaled_wns_500/'
noise_filename = noise_dir + 'wns_9520_forscaled.txt'
downsample_dir = project_dir + 'bhalla_scaled_9520_downsampled/'

os.chdir(project_dir)

from neuron import h, gui

h.load_file('stdgui.hoc')
h.load_file('stdrun.hoc')

h.load_file('cell.hoc')

# create a Shape plot object
morph = h.Shape()

# 3d plot shape options
morph.show(0)   # show as filled volume
morph.show(1)   # show as lines through centroids
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
Ejemplo n.º 7
0
def plotShape(axis=None,
              includePre=['all'],
              includePost=['all'],
              showSyns=False,
              showElectrodes=False,
              synStyle='.',
              synSize=3,
              dist=0.6,
              elev=90,
              azim=-90,
              cvar=None,
              cvals=None,
              clim=None,
              iv=False,
              ivprops=None,
              includeAxon=True,
              bkgColor=None,
              aspect='auto',
              axisLabels=False,
              kind='shape',
              returnPlotter=False,
              **kwargs):
    """
    Function to plot morphology of network>
    """

    from .. import sim
    from neuron import h

    print('Plotting 3D cell shape ...')

    cellsPreGids = [c.gid for c in sim.getCellsList(includePre)
                    ] if includePre else []
    cellsPost = sim.getCellsList(includePost)

    if not hasattr(sim.net, 'compartCells'):
        sim.net.compartCells = [
            c for c in cellsPost if type(c) is sim.CompartCell
        ]
    try:
        sim.net.defineCellShapes(
        )  # in case some cells had stylized morphologies without 3d pts
    except:
        pass

    saveFig = False
    if 'saveFig' in kwargs:
        saveFig = kwargs['saveFig']

    fontSize = None
    if 'fontSize' in kwargs:
        fontSize = kwargs['fontSize']

    if not iv:  # plot using Python instead of interviews
        from mpl_toolkits.mplot3d import Axes3D
        from netpyne.support import morphology as morph  # code adapted from https://github.com/ahwillia/PyNeuron-Toolbox

        # create secList from include
        secs = None

        # Set cvals and secs
        if not cvals and cvar:
            cvals = []
            secs = []
            # weighNorm
            if cvar == 'weightNorm':
                for cellPost in cellsPost:
                    cellSecs = list(
                        cellPost.secs.values()) if includeAxon else [
                            s for s in list(cellPost.secs.values())
                            if 'axon' not in s['hObj'].hname()
                        ]
                    for sec in cellSecs:
                        if 'weightNorm' in sec:
                            secs.append(sec['hObj'])
                            cvals.extend(sec['weightNorm'])

                cvals = np.array(cvals)
                cvals = cvals / min(cvals)

            # numSyns
            elif cvar == 'numSyns':
                for cellPost in cellsPost:
                    cellSecs = cellPost.secs if includeAxon else {
                        k: s
                        for k, s in cellPost.secs.items()
                        if 'axon' not in s['hObj'].hname()
                    }
                    for secLabel, sec in cellSecs.items():
                        nseg = sec['hObj'].nseg
                        nsyns = [0] * nseg
                        secs.append(sec['hObj'])
                        conns = [
                            conn for conn in cellPost.conns
                            if conn['sec'] == secLabel
                            and conn['preGid'] in cellsPreGids
                        ]
                        for conn in conns:
                            nsyns[int(ceil(conn['loc'] * nseg)) - 1] += 1
                        cvals.extend(nsyns)

                cvals = np.array(cvals)

            # voltage
            elif cvar == 'voltage':
                for cellPost in cellsPost:
                    cellSecs = cellPost.secs if includeAxon else {
                        k: s
                        for k, s in cellPost.secs.items()
                        if 'axon' not in s['hObj'].hname()
                    }
                    for secLabel, sec in cellSecs.items():
                        for seg in sec['hObj']:
                            cvals.append(seg.v)

                cvals = np.array(cvals)

        if not isinstance(cellsPost[0].secs, dict):
            print('Error: Cell sections not available')
            return -1

        if not secs:
            secs = [
                s['hObj'] for cellPost in cellsPost
                for s in list(cellPost.secs.values())
            ]
        if not includeAxon:
            secs = [sec for sec in secs if 'axon' not in sec.hname()]

        # Plot shapeplot
        cbLabels = {
            'numSyns': 'Number of synapses per segment',
            'weightNorm': 'Weight scaling',
            'voltage': 'Voltage (mV)'
        }
        #plt.rcParams.update({'font.size': fontSize})

        if axis is None:
            metaFig = MetaFigure(kind=kind, subplots=None, **kwargs)
            fig = metaFig.fig
            metaFig.ax.remove()
            shapeax = fig.add_subplot(111, projection='3d')
            metaFig.ax = shapeax
        else:
            shapeax = axis
            fig = axis.figure
            metafig = fig.metafig
            numRows = np.shape(metafig.ax)[0]
            numCols = np.shape(metafig.ax)[1]
            axisLoc = np.where(metafig.ax.ravel() == shapeax)[0][0] + 1
            plt.delaxes(shapeax)
            figIndex = int(str(numRows) + str(numCols) + str(axisLoc))
            shapeax = fig.add_subplot(figIndex, projection='3d')

        shapeax.elev = elev  # 90
        shapeax.azim = azim  # -90
        shapeax.dist = dist * shapeax.dist
        plt.axis(aspect)
        cmap = plt.cm.viridis  #plt.cm.jet  #plt.cm.rainbow #plt.cm.jet #YlOrBr_r
        morph.shapeplot(h,
                        shapeax,
                        sections=secs,
                        cvals=cvals,
                        cmap=cmap,
                        clim=clim)

        # fix so that axes can be scaled
        ax = plt.gca()

        def set_axes_equal(ax):
            """Set 3D plot axes to equal scale.

            Make axes of 3D plot have equal scale so that spheres appear as
            spheres and cubes as cubes.  Required since `ax.axis('equal')`
            and `ax.set_aspect('equal')` don't work on 3D.
            """
            limits = np.array([
                ax.get_xlim3d(),
                ax.get_ylim3d(),
                ax.get_zlim3d(),
            ])
            origin = np.mean(limits, axis=1)
            radius = 0.5 * np.max(np.abs(limits[:, 1] - limits[:, 0]))
            _set_axes_radius(ax, origin, radius)

        def _set_axes_radius(ax, origin, radius):
            x, y, z = origin
            ax.set_xlim3d([x - radius, x + radius])
            ax.set_ylim3d([y - radius, y + radius])
            ax.set_zlim3d([z - radius, z + radius])

        ax.set_box_aspect([1, 1, 1])  # IMPORTANT - this is the new, key line
        set_axes_equal(ax)

        fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
        if cvals is not None and len(cvals) > 0:
            vmin = np.min(cvals)
            vmax = np.max(cvals)

            if clim is not None:
                vmin = np.min(clim)
                vmax = np.max(clim)

            sm = plt.cm.ScalarMappable(cmap=cmap,
                                       norm=plt.Normalize(vmin=vmin,
                                                          vmax=vmax))
            sm._A = []  # fake up the array of the scalar mappable
            cb = plt.colorbar(sm,
                              fraction=0.15,
                              shrink=0.5,
                              pad=0.05,
                              aspect=20)
            if cvar:
                cb.set_label(cbLabels[cvar], rotation=90, fontsize=fontSize)

            if saveFig == 'movie':
                cb.ax.set_title('Time = ' + str(round(h.t, 1)),
                                fontsize=fontSize)

        if bkgColor:
            shapeax.w_xaxis.set_pane_color(bkgColor)
            shapeax.w_yaxis.set_pane_color(bkgColor)
            shapeax.w_zaxis.set_pane_color(bkgColor)
        #shapeax.grid(False)

        # Synapses
        if showSyns:
            synColor = 'red'
            for cellPost in cellsPost:
                for sec in list(cellPost.secs.values()):
                    for synMech in sec['synMechs']:
                        morph.mark_locations(h,
                                             sec['hObj'],
                                             synMech['loc'],
                                             markspec=synStyle,
                                             color=synColor,
                                             markersize=synSize)

        # Electrodes
        if showElectrodes:
            ax = plt.gca()
            colorOffset = 0
            if 'avg' in showElectrodes:
                showElectrodes.remove('avg')
                colorOffset = 1
            coords = sim.net.recXElectrode.pos.T[
                np.array(showElectrodes).astype(int), :]
            ax.scatter(coords[:, 0],
                       coords[:, 1],
                       coords[:, 2],
                       s=150,
                       c=colorList[colorOffset:len(coords) + colorOffset],
                       marker='v',
                       depthshade=False,
                       edgecolors='k',
                       linewidth=2)
            for i in range(coords.shape[0]):
                ax.text(coords[i, 0],
                        coords[i, 1],
                        coords[i, 2],
                        '  ' + str(showElectrodes[i]),
                        fontweight='bold')
            cb.set_label(
                'Segment total transfer resistance to electrodes (kiloohm)',
                rotation=90,
                fontsize=fontSize)

        if axisLabels:
            shapeax.set_xlabel('x (um)')
            shapeax.set_ylabel('y (um)')
            shapeax.set_zlabel('z (um)')
        else:
            shapeax.set_xticklabels([])
            shapeax.set_yticklabels([])
            shapeax.set_zticklabels([])

        if axis is None:
            metaFig.finishFig(**kwargs)
        else:
            if saveFig:
                if isinstance(saveFig, basestring):
                    if saveFig == 'movie':
                        filename = sim.cfg.filename + '_shape_movie_' + str(
                            round(h.t, 1)) + '.png'
                    else:
                        filename = saveFig
                else:
                    filename = sim.cfg.filename + '_shape.png'
                plt.savefig(filename, dpi=dpi)

            # show fig
            # if showFig: _showFigure()

    else:  # Plot using Interviews
        # colors: 0 white, 1 black, 2 red, 3 blue, 4 green, 5 orange, 6 brown, 7 violet, 8 yellow, 9 gray
        from neuron import gui
        fig = h.Shape()
        secList = h.SectionList()
        if not ivprops:
            ivprops = {'colorSecs': 1, 'colorSyns': 2, 'style': 'O', 'siz': 5}

        for cell in [c for c in cellsPost]:
            for sec in list(cell.secs.values()):
                if 'axon' in sec['hObj'].hname() and not includeAxon: continue
                sec['hObj'].push()
                secList.append()
                h.pop_section()
                if showSyns:
                    for synMech in sec['synMechs']:
                        if synMech['hObj']:
                            # find pre pop using conn[preGid]
                            # create dict with color for each pre pop; check if exists; increase color counter
                            # colorsPre[prePop] = colorCounter

                            # find synMech using conn['loc'], conn['sec'] and conn['synMech']
                            fig.point_mark(synMech['hObj'],
                                           ivprops['colorSyns'],
                                           ivprops['style'], ivprops['siz'])

        fig.observe(secList)
        fig.color_list(secList, ivprops['colorSecs'])
        fig.flush()
        fig.show(0)  # show real diam
        # save figure
        if saveFig:
            if isinstance(saveFig, basestring):
                filename = saveFig
            else:
                filename = sim.cfg.filename + '_' + 'shape.ps'
            fig.printfile(filename)

    if not iv:
        if axis is None:
            if returnPlotter:
                return metaFig
            else:
                return fig, {}
        else:
            return fig, {}

    else:
        return fig, {}
Ejemplo n.º 8
0
Vsoma = h.Vector()
Vsoma.record(HCell.soma[0](.5)._ref_v)
tvec = h.Vector()
tvec.record(h._ref_t)

h.init(h.v_init)
h.run()

np_t = np.array(tvec)
np_v =  np.array(Vsoma)

plt.plot(np_t,np_v,c='g')
plt.xlim(100,250)
plt.ylim(-100,50)

shp = h.Shape()
shp.rotate(0,0,0,0,0,3.4)

shp.show(0)
for i in range(NUMBER_OF_SYNAPSES):
    shp.point_mark(SynList[i], 4,4,6)

shp.view(-400,-600,800,1600,800,0,400,800)


ps = h.PlotShape() 
ps.exec_menu("View = plot")
ps.rotate(0,0,0,0,0,3.4)
ps.view(-400,-600,800,1600,800,0,400,800)
ps.variable("v")
h.load_file("../NEURON_color_maps/TColorMap.hoc")
Ejemplo n.º 9
0
# c(1)->b(1): green->blue
# d(0)->b(1): yellow->blue
# e(0)->a(0): black->red

a, b, c, d, e = [h.Section(name=n) for n in ['a', 'b', 'c', 'd', 'e']]
b.connect(a)
c.connect(b(1), 1)  # connect the 1 end of c to the 1 end of b
d.connect(b)
e.connect(a(0))  # connect the 0 end of e to the 0 end of a
for sec in h.allsec():
    sec.nseg = 20
    sec.L = 100
    for seg in sec:
        seg.diam = numpy.interp(seg.x, [0, 1], [10, 40])

s = h.Shape()
s.show(False)

s.color(2, sec=a)  # a - red
s.color(3, sec=b)  # b - blue
s.color(4, sec=c)  # c - green
s.color(5, sec=d)  # d - yellow
s.color(1, sec=e)  # e - black
h.topology()
h.finitialize()
for sec in h.allsec():
    print(sec)
    for i in range(sec.n3d()):
        print('%d: (%g, %g, %g; %g)' %
              (i, sec.x3d(i), sec.y3d(i), sec.z3d(i), sec.diam3d(i)))
Ejemplo n.º 10
0
if __name__ == '__main__':  #this is extremely important for python scripts in windows
    filePath = 'C:/Users/mach5/OneDrive/Desktop/SM_granule_golgi_models/data.hdf5'
    file2 = 'C:/Users/mach5/OneDrive/Desktop/SM_granule_golgi_models/dataPurk.hdf5'
    if os.path.exists(filePath):
        os.remove(filePath)
    else:
        print 'cannot delete file as it is not there'
    if os.path.exists(file2):
        os.remove(file2)
    else:
        print 'file 2 is not there'

    #del data.hdf5
    #del dataPurk.hdf5
    start = timeit.default_timer()
    pool = mp.Pool(8)
    #grcs=[pool.apply_async(setup_grcmorphology,args=(i, grcpositions[i,2], grcpositions[i,4], grcpositions[i,3])) for i in range(100)]
    #pcs=[pool.apply_async(setup_pcmorphology,args=(i,pcpositions[i,2],pcpositions[i,4],pcpositions[i,3])) for i in range(10)]

    pcs = [
        setup_pcmorphology(i, pcpositions[i, 2], pcpositions[i, 4],
                           pcpositions[i, 3]) for i in range(1)
    ]
    stop = timeit.default_timer()
    print('Time:', stop - start)
    #pool.close()
    #pool.join()
    #grcs=[setup_grcmorphology(i,grcpositions[i,2],grcpositions[i,4],grcpositions[i,3]) for i in range(100)]
    slt = h.Shape()
    slt.view()
Ejemplo n.º 11
0
    plot_synapses(shp,putative_dict,"110426_Sl4_Cl2_4to6",Synlist,COLOR_MAGENTA)


def plot_fig1C2(putative_dict,Synlist):

    plot_synapses(shp2,putative_dict,"110426_Sl4_Cl2_6to4",Synlist,COLOR_BLUE)
    plot_synapses(shp2,putative_dict,"110322_Sl2_Cl2_6to4",Synlist,COLOR_ORANGE)



Synlist = []
for sec in HCell.basal:
    sec.diam = sec.diam*ThickFactor
for sec in HCell.apical:
    sec.diam = sec.diam*ThickFactor

putative_dict = putative_synapses()
shp = h.Shape()
shp.show(0)
shp.rotate(0,0,0,0,0,2.8)
shp.view(-400,-600,1000,1700,0,0,800,800)
plot_synapses(shp,putative_dict,"081212_1to5",Synlist,COLOR_RED)
plot_synapses(shp,putative_dict,"110426_Sl4_Cl2_4to6",Synlist,COLOR_MAGENTA)

shp2 = h.Shape()
shp2.show(0)
shp2.rotate(0,0,0,0,0,2.8)
shp2.view(-400,-600,1000,1700,400,0,800,800)
plot_synapses(shp2,putative_dict,"110426_Sl4_Cl2_6to4",Synlist,COLOR_BLUE)
plot_synapses(shp2,putative_dict,"110322_Sl2_Cl2_6to4",Synlist,COLOR_ORANGE)
Ejemplo n.º 12
0
def SE_3D(
    S,
    Simdur=400.0,
    dt=0.01,
    G_EoH=0.055,
    StochasticEoH=True,
    N=32,
    G_Dend=0.032,
    tau_Dend=2.0,
    gKLT_d=0.0085,
    gIH_d=0.001,
    gLEAK_d=0.001,  # here was 0.0001, 10x the Rm of the stylized? That seemed wrong (TK)
    gKLT_s=0.017,
    gIH_s=0.002,
    cell=1,
    debug=False,
    EoHseed=-1,
    somaticsynapsesonly=0,
    impedancetesting=0,
    impstim=(0.1, 50.0, 0.0),
    Ra=150.0,
    impdendtype=0,
    impdendid=-1,
    listinfo=False,
    minD=1.0,
):
    """
    Build one of the reconstructed gerbil SBC and give them biophysics.

    0: The "Ycell" (cell 0) is a dummy cell.
    1: SBC 1220
    2: SBC 0119
    3: SBC 1220b
    4: SBC 0119 simplified (was used for debugging the 3D geometry)

    Input Spiketimes are generated outside. Remember, you need N+1 spiketrains
    for the synapses (N x dendritic + endbulb)

    If you pass somaticsynapsesonly=1 then all the small synapses will be located on
    the soma (as requested by reviewer 2 for the JNP submission)

    If you pass impedancetesting=1, than a single current source will be attached to
    the distal end of a distal dendrite and a sinusoidal current of
    impstim[0] Amplitude,impstim[1] frequency and impstim[2] phase will be played.
    No synaptic events will occur in this case.
    If you pass impedancetesting=-1, than the same as above but a chirp stim is used
    which will defined by impfreq[0]->impfreq[1].
    impdendtype (default = 0): 0-> connect distal dendrite, 1->proximal dendrite
    imdendid (default = -1): which dendrite of type impdendtype to connect

    Modified from original code by Elisabeth Koert, 2018
    created by Thomas Künzel, 2019-06-28
    modified by Thomas Künzel, sept 2020
    """
    pretime = 100.0  # ms
    #
    # Check for impedancetesting and if the user wants it, blank all synaptic inputs
    if impedancetesting == 1 or impedancetesting == -1:
        G_Dend = 0.0
        G_EoH = 0.0
        from scipy.signal import chirp
    #
    if cell == 0:
        cellname = "Ycell"
    elif cell == 1:
        cellname = "1220"
    elif cell == 2:
        cellname = "0119"
    elif cell == 3:
        cellname = "1220b"
    elif cell == 4:
        cellname = "0119simple"
    #
    # create the model
    # soma, ais, axon, proximal, distal = load3D(
    #    cell=cellname, debug=debug
    # )  # see function above
    soma, ais, axon, proximal, distal = load3Dnew(
        cell=cellname,
        debug=debug,
        minD=minD,
    )
    if listinfo:
        nprox = len(proximal)
        ndist = len(distal)
        return nprox, ndist
    # axial Resistance and cm
    for sec in h.allsec():
        sec.Ra = Ra
        sec.insert("extracellular")
    axon.cm = 0.1
    # na
    soma.insert("na_fast")
    soma.ena = 50
    soma.gnabar_na_fast = 0.01  # old ball and stick value was 1e-9
    ais.insert("na_fast")
    ais.ena = 50
    ais.gnabar_na_fast = 0.53
    # klt
    soma.insert("klt")
    soma.ek = -70
    soma.gkltbar_klt = gKLT_s
    ais.insert("klt")
    ais.ek = -70
    ais.gkltbar_klt = gKLT_s
    # kht
    soma.insert("kht")
    soma.gkhtbar_kht = 0.013
    ais.insert("kht")
    ais.ek = -70
    ais.gkhtbar_kht = 0.013
    # ih
    soma.insert("ih")
    h.eh_ih = -43
    soma.ghbar_ih = gIH_s
    for i in range(len(proximal)):
        proximal[i].insert("ih")
        proximal[i].ghbar_ih = gIH_d
        proximal[i].insert("klt")
        proximal[i].gkltbar_klt = gKLT_d
    # leak
    for sec in h.allsec():
        sec.insert("leak")
        sec.erev_leak = -65
        sec.g_leak = gLEAK_d
    axon.g_leak = 0.0001
    # GENERAL SETTINGS
    h.dt = dt  # simulation (or "sampling") rate
    h.celsius = 35  # simulation global temperature
    # shape the endbulb input
    EoH_Template = seh.g_template(dt=dt, gmax=G_EoH)
    g_exc = seh.make_g_trace(
        Simdur + pretime, dt, S[-1] + pretime, EoH_Template, StochasticEoH, 0.1, EoHseed
    )  # Last spiketimes are for endbulbs
    gv_exc = h.Vector(g_exc)
    endbulb = h.GClamp(0.4, sec=soma)
    endbulb.e = 0
    gv_exc.play(endbulb._ref_g, h.dt)
    # sloc file containing locations for "randomly" placed synapses -- so they
    # are more reproducible
    slocfilename = "./cells/" + cellname + "/" + cellname + ".npy"
    if os.path.isfile(slocfilename):
        has_sloc = True
        try:
            sloc = np.load(slocfilename, allow_pickle=True)
        except:
            has_sloc = False
        if sloc.shape[0] != N:
            has_sloc = False
    else:
        has_sloc = False
    if not has_sloc:
        sloc = np.zeros((N, 4))
    # shape the small synapses
    if N != 0:
        vstim = []
        syna = []
        netcon = []
        G_i = G_Dend / N  # individual conductance
        pos = np.linspace(0.05, 0.95, N)
        for a in range(N):
            if somaticsynapsesonly == 1:
                syna.append(h.ExpSyn(soma(pos[a])))
                syna[a].tau = tau_Dend
            else:
                # define synapse position randomly or from file:
                if has_sloc:
                    onproximal = bool(sloc[a, 0])
                    thispos = sloc[a, 1]
                    whichdistal = int(sloc[a, 2])
                    whichproximal = int(sloc[a, 3])
                else:
                    if np.random.random() > 0.66:
                        onproximal = True
                    else:
                        onproximal = False
                    thispos = np.random.random()  # random position on dendrite
                    whichdistal = np.random.randint(
                        0, len(distal) - 1
                    )  # random distal dendrite
                    whichproximal = np.random.randint(
                        0, len(proximal) - 1
                    )  # random distal dendrite
                    sloc[a, 0] = float(onproximal)
                    sloc[a, 1] = thispos
                    sloc[a, 2] = float(whichdistal)
                    sloc[a, 3] = float(whichproximal)
                if onproximal:
                    syna.append(h.ExpSyn(proximal[whichproximal](thispos)))
                    syna[a].tau = tau_Dend
                else:
                    syna.append(h.ExpSyn(distal[whichdistal](thispos)))
                    syna[a].tau = tau_Dend
            # synapse stimulieren
            vstim.append(h.VecStim())
            netcon.append(h.NetCon(vstim[a], syna[a]))  # connect stimulus and synapse
            netcon[a].weight[0] = G_i
            spt = h.Vector(S[a] + pretime)
            vstim[a].play(spt)
    if not has_sloc:
        if not somaticsynapsesonly == 1:
            np.save(slocfilename, sloc)
    #
    # Input for impedance testing (as requested by reviewer)
    if impedancetesting == 1 or impedancetesting == -1:
        if impdendtype == 0:
            impclamp = h.IClamp(distal[impdendid](0.99))
            impathlen = h.distance(soma(0.5), distal[impdendid](0.99))
        else:
            impclamp = h.IClamp(proximal[impdendid](0.99))
            impathlen = h.distance(soma(0.5), proximal[impdendid](0.99))
        impclamp.delay = 0.0
        impclamp.dur = 1e9
        impclamp.amp = 0.0
        if impedancetesting == -1:
            t = np.linspace(0.0, Simdur - dt, int(Simdur / dt))
            tsec = t / 1000.0
            impwave = impstim[0] * chirp(
                tsec,
                f0=impstim[1][0],
                f1=impstim[1][1],
                t1=tsec[-1],
                method="linear",
            )
        else:
            t = np.linspace(0.0, Simdur - dt, int(Simdur / dt))
            f = impstim[1] / 1000.0
            impwave = impstim[0] * np.sin(2.0 * np.pi * f * t + impstim[2])
        prezeros = np.zeros(int(round(pretime / dt)))
        impwave = np.concatenate((prezeros, impwave))
        impwave = h.Vector(impwave)
        tvec = np.linspace(0.0, (Simdur + pretime) - dt, (Simdur + pretime) / dt)
        tvec = h.Vector(tvec)
        impwave.play(impclamp._ref_amp, tvec)
    else:
        impathlen = -1
    #
    if debug:
        from neuron import gui

        basename = "figs/shape"
        s = h.Shape()
        s.show(0)
        s.color(2, sec=soma)
        s.color(2, sec=axon)
        s.color(2, sec=ais)
        for pcount, thisprox in enumerate(proximal):
            s.color(3 + pcount, sec=thisprox)
        if impedancetesting == 1:
            s.point_mark(impclamp, 3)
            s.label(0, 0, str(impathlen))
            varname = "_c" + str(cell) + "_t" + str(impdendtype) + "_d" + str(impdendid)
            filename = basename + varname + ".ps"
        else:
            varname = "_c" + str(cell) + "_syn"
            filename = basename + varname + ".ps"
            for a in range(N):
                s.point_mark(syna[a], 3)
        # input("Press Enter to continue...")###uncomment if you want interactive plot
        s.printfile(filename)
    #
    # INFRASTRUCTURE
    Vm = h.Vector()
    Vm.record(soma(0.5)._ref_v)
    #
    # ----------SIMULATE--------------
    h.finitialize(-63.79)
    h.fcurrent()
    while h.t < Simdur + pretime:
        h.fadvance()
    #
    # PACK AND EXPORT DATA
    Result = {}
    tempres_vm = np.array(Vm)
    Result["Vm"] = tempres_vm[
        int(pretime / dt) : int((Simdur + pretime) / dt)
    ]  # remove "additional" samples
    Result["impathlen"] = impathlen
    #
    # ---------SAY GOODBYE-------------
    return Result