Beispiel #1
0
    def loadTTreeTestChannel(self):
        """
        Load the T-tree morphology in memory with h-current

          6--5--4--7--8
                |
                |
                1
        """
        v_eq = -75.
        self.dt = 0.025
        self.tmax = 100.
        # for frequency derivation
        self.ft = ke.FourrierTools(np.arange(0., self.tmax, self.dt))
        # load the morphology
        test_chan = channelcollection.TestChannel2()
        fname = os.path.join(MORPHOLOGIES_PATH_PREFIX, 'Tsovtree.swc')
        self.greenstree = GreensTree(fname, types=[1, 3, 4])
        self.greenstree.addCurrent(test_chan, 50., -23.)
        self.greenstree.fitLeakCurrent(v_eq, 10.)
        self.greenstree.setCompTree()
        self.greenstree.setImpedance(self.ft.s)
        # copy greenstree parameters into NEURON simulation tree
        self.neurontree = NeuronSimTree(dt=self.dt,
                                        t_calibrate=100.,
                                        v_init=v_eq,
                                        factor_lambda=25.)
        self.greenstree.__copy__(self.neurontree)
        self.neurontree.treetype = 'computational'
Beispiel #2
0
    def loadTTreeActive(self):
        """
        Load the T-tree morphology in memory with h-current

          6--5--4--7--8
                |
                |
                1
        """
        v_eq = -75.
        self.dt = 0.1
        self.tmax = 100.
        # for frequency derivation
        self.ft = ke.FourrierTools(np.arange(0., self.tmax, self.dt))
        # load the morphology
        print('>>> loading T-tree <<<')
        h_chan = channelcollection.h()
        fname = 'test_morphologies/Tsovtree.swc'
        self.greenstree = GreensTree(fname, types=[1, 3, 4])
        self.greenstree.addCurrent(h_chan, 50., -43.)
        self.greenstree.fitLeakCurrent(v_eq, 10.)
        self.greenstree.setCompTree()
        self.greenstree.setImpedance(self.ft.s)
        # copy greenstree parameters into NEURON simulation tree
        self.neurontree = NeuronSimTree(dt=self.dt,
                                        t_calibrate=10.,
                                        v_init=v_eq,
                                        factor_lambda=25.)
        self.greenstree.__copy__(self.neurontree)
        self.neurontree.treetype = 'computational'
Beispiel #3
0
    def __init__(self):

        channel_names = ['L', 'K_ir', 'K_m35']

        # reduced trees
        full_tree, red_tree, self.full_locs, self.red_locs = data.reduceMorphology(
        )
        sim_tree = red_tree.__copy__(new_tree=NeuronSimTree())
        # measured data
        self.v_dat = data.DataContainer(with_zd=True)
        # get file name
        file_name = utils.getFileName(channel_names, True, suffix='_predef')

        print(file_name)
        # load hall of fame
        with open(file_name, 'rb') as file:
            hall_of_fame = pickle.load(file)
        # get the original simtree with the potassium params
        self.model_evaluator = optimizer.ModelEvaluator(
            sim_tree,
            self.v_dat,
            self.red_locs[0],
            self.red_locs[1],
            channel_names=channel_names,
            mode='evaluate')
        self.model_evaluator.setParameterValues(hall_of_fame[0])

        self._createHcnTees()
        self._createGreensTrees()
Beispiel #4
0
def optimizeModel(channel_names=None, zd=False, suffix=''):
    """
    Optimizes the morphology equipped with channels in `channel_names` to
    recordings with or without ZD

    Parameters
    ----------
    channel_names: list of str
        Choose channel names from from {'L', 'K_m', 'K_m35', 'K_ir', 'h_HAY', 'h_u'}
    zd: bool
        True for data with ZD, false for data without ZD
    """
    global MAX_ITER, N_OFFSPRING

    if channel_names is None:
        channel_names = ['L', 'K_ir', 'K_m35', 'h_u']
    file_name = utils.getFileName(channel_names, zd, suffix=suffix)

    full_tree, red_tree, full_locs, red_locs = data.reduceMorphology()
    sim_tree = red_tree.__copy__(new_tree=NeuronSimTree())

    # measured data
    v_dat = data.DataContainer(with_zd=zd)
    model_evaluator = ModelEvaluator(sim_tree,
                                     v_dat,
                                     red_locs[0],
                                     red_locs[1],
                                     channel_names=channel_names)

    final_pop, hall_of_fame, logs, hist = optimize(model_evaluator)

    # save hall of fame
    file = open(file_name, 'wb')
    pickle.dump(hall_of_fame, file)
    file.close()
Beispiel #5
0
    def createPointNeurons(self, v_eq=-75.):
        self.v_eq = v_eq
        self.dt = .025
        gh, eh = 50., -43.
        h_chan = channelcollection.h()

        self.greens_tree = GreensTree(
            file_n=os.path.join(MORPHOLOGIES_PATH_PREFIX, 'ball.swc'))
        self.greens_tree.setPhysiology(1., 100. / 1e6)
        self.greens_tree.addCurrent(h_chan, gh, eh)
        self.greens_tree.fitLeakCurrent(v_eq, 10.)
        self.greens_tree.setEEq(v_eq)
        self.greens_tree_pas = self.greens_tree.__copy__(new_tree=GreensTree())
        self.greens_tree_pas.asPassiveMembrane()
        self.sim_tree = self.greens_tree.__copy__(new_tree=NeuronSimTree())
        # set the impedances
        self.greens_tree_pas.setCompTree()
        self.freqs = np.array([0.])
        self.greens_tree_pas.setImpedance(self.freqs)
        # create sov tree
        self.sov_tree = self.greens_tree_pas.__copy__(new_tree=SOVTree())
        self.sov_tree.calcSOVEquations(maxspace_freq=50.)

        z_inp = self.greens_tree_pas.calcZF((1, .5), (1, .5))[0]
        alphas, gammas = self.sov_tree.getSOVMatrices(locarg=[(1., .5)])
        # create NET
        node_0 = NETNode(0, [0], [0], z_kernel=(alphas, gammas[:, 0]**2))
        net_py = NET()
        net_py.setRoot(node_0)
        # check if correct
        assert np.abs(gammas[0, 0]**2 / np.abs(alphas[0]) - z_inp) < 1e-10
        assert np.abs(node_0.z_bar - z_inp) < 1e-10

        # to initialize neuron tree
        self.sim_tree.initModel(dt=self.dt)
        # add ion channel to NET simulator
        a_soma = 4. * np.pi * (self.sim_tree[1].R * 1e-4)**2
        self.cnet = netsim.NETSim(net_py, v_eq=self.v_eq)

        hchan = channelcollection.h()
        self.cnet.addChannel(hchan, 0, gh * a_soma, eh)

        # add the synapse
        # to neuron tree
        self.sim_tree.addDoubleExpSynapse((1, .5), .2, 3., 0.)
        self.sim_tree.setSpikeTrain(0, 0.001, [5.])
        # to net sim
        self.cnet.addSynapse(0, {
            'tau_r': .2,
            'tau_d': 3.,
            'e_r': 0.
        },
                             g_max=0.001)
        self.cnet.setSpikeTimes(0, [5. + self.dt])
Beispiel #6
0
    def loadTTreeTestChannelSoma(self):
        """
        Load the T-tree morphology in memory with h-current

          6--5--4--7--8
                |
                |
                1
        """
        v_eq = -75.
        self.dt = 0.025
        self.tmax = 100.
        # for frequency derivation
        self.ft = ke.FourrierTools(np.arange(0., self.tmax, self.dt))
        # load the morphology
        print('>>> loading T-tree <<<')
        test_chan = channelcollection.TestChannel2()
        fname = 'test_morphologies/Tsovtree.swc'
        self.greenstree = GreensTree(fname, types=[1, 3, 4])
        self.greenstree.addCurrent(test_chan,
                                   50.,
                                   23.,
                                   node_arg=[self.greenstree[1]])
        self.greenstree.fitLeakCurrent(v_eq, 10.)
        # for node in self.greenstree:
        #     print node.getGTot(channel_storage=self.greenstree.channel_storage)
        #     print node.currents
        self.greenstree.setCompTree()
        self.greenstree.setImpedance(self.ft.s)
        # copy greenstree parameters into NEURON simulation tree
        self.neurontree = NeuronSimTree(dt=self.dt,
                                        t_calibrate=100.,
                                        v_init=v_eq,
                                        factor_lambda=25.)
        self.greenstree.__copy__(self.neurontree)
        self.neurontree.treetype = 'computational'
Beispiel #7
0
def runCalciumCoinc(recompute_ctree=False,
                    recompute_biophys=False,
                    axdict=None,
                    pshow=True):
    global D2S_CASPIKE, D2S_APIC
    global CA_LOC

    lss_ = ['-', '-.', '--']
    css_ = [colours[3], colours[0], colours[1]]
    lws_ = [.8, 1.2, 1.6]

    # create the full model
    phys_tree = getL5Pyramid()
    sim_tree = phys_tree.__copy__(new_tree=NeuronSimTree())
    # compartmentfitter object
    cfit = CompartmentFitter(phys_tree, name='bac_firing', path='data/')

    # single branch initiation zone
    branch = sim_tree.pathToRoot(sim_tree[236])[::-1]
    locs_sb = sim_tree.distributeLocsOnNodes(D2S_CASPIKE,
                                             node_arg=branch,
                                             name='single branch')
    # abpical trunk locations
    apic = sim_tree.pathToRoot(sim_tree[221])[::-1]
    locs_apic = sim_tree.distributeLocsOnNodes(D2S_APIC,
                                               node_arg=apic,
                                               name='apic connection')

    # store set of locations
    fit_locs = [(1, .5)] + locs_apic + locs_sb
    sim_tree.storeLocs(fit_locs, name='ca coinc')
    # PSP input location index
    ca_ind = sim_tree.getNearestLocinds([CA_LOC], name='ca coinc')[0]

    # obtain the simplified tree
    ctree, clocs = getCTree(cfit,
                            fit_locs,
                            'data/ctree_bac_firing',
                            recompute_biophys=recompute_biophys,
                            recompute_ctree=recompute_ctree)

    # print(ctree)
    print('--- ctree nodes currents')
    print('\n'.join([str(n.currents) for n in ctree]))

    reslist, creslist_sb, creslist_sb_ = [], [], []
    locindslist_sb, locindslist_apic_sb = [], []

    if axdict is None:
        pl.figure('inp')
        axes_input = [pl.subplot(131), pl.subplot(132), pl.subplot(133)]
        pl.figure('V trace')
        axes_trace = [pl.subplot(131), pl.subplot(132), pl.subplot(133)]
        pl.figure('morph')
        axes_morph = [pl.subplot(121), pl.subplot(122)]
    else:
        axes_input = axdict['inp']
        axes_trace = axdict['trace']
        axes_morph = axdict['morph']
        pshow = False

    for jj, stim in enumerate(['current', 'psp', 'coinc']):
        print('--- sim full  ---')
        rec_locs = sim_tree.getLocs('ca coinc')
        # runn the simulation
        res = runCaCoinc(sim_tree,
                         rec_locs,
                         ca_ind,
                         0,
                         stim_type=stim,
                         rec_kwargs=dict(record_from_syns=True,
                                         record_from_iclamps=True))

        print('---- sim reduced ----')
        rec_locs = clocs
        # run the simulation of the reduced tree
        csim_tree = createReducedNeuronModel(ctree)
        cres = runCaCoinc(csim_tree,
                          rec_locs,
                          ca_ind,
                          0,
                          stim_type=stim,
                          rec_kwargs=dict(record_from_syns=True,
                                          record_from_iclamps=True))

        id_offset = 1.
        vd_offset = 7.2
        vlim = (-80., 20.)
        ilim = (-.1, 2.2)

        # input current
        ax = axes_input[jj]
        ax.plot(res['t'], -res['i_clamp'][0], c='r', lw=lwidth)
        ax.plot(res['t'], res['i_syn'][0] + id_offset, c='b', lw=lwidth)

        ax.set_yticks([0., id_offset])
        if jj == 1 or jj == 2:
            drawScaleBars(ax, ylabel=' nA', b_offset=0)
        else:
            drawScaleBars(ax)
        if jj == 2:
            ax.set_yticklabels([r'Soma', r'Dend'])

        ax.set_ylim(ilim)

        # somatic trace
        ax = axes_trace[jj]
        ax.set_xticks([0., 50.])
        ax.plot(res['t'], res['v_m'][0], c='DarkGrey', lw=lwidth)
        ax.plot(cres['t'], cres['v_m'][0], c=cll[0], lw=1.6 * lwidth, ls='--')

        # dendritic trace
        ax.plot(res['t'],
                res['v_m'][ca_ind] + vd_offset,
                c='DarkGrey',
                lw=lwidth)
        ax.plot(cres['t'],
                cres['v_m'][ca_ind] + vd_offset,
                c=cll[1],
                lw=1.6 * lwidth,
                ls='--')

        ax.set_yticks([cres['v_m'][0][0], cres['v_m'][ca_ind][0] + vd_offset])
        if jj == 1 or jj == 2:
            drawScaleBars(ax, xlabel=' ms', ylabel=' mV', b_offset=15)
            # drawScaleBars(ax, xlabel=' ms', b_offset=25)
        else:
            drawScaleBars(ax)
        if jj == 2:
            ax.set_yticklabels([r'Soma', r'Dend'])
        ax.set_ylim(vlim)

    print('iv')

    plocs = sim_tree.getLocs('ca coinc')
    markers = [{'marker': 's', 'mfc': cfl[0], 'mec': 'k', 'ms': markersize/1.1}] + \
              [{'marker': 's', 'mfc': cfl[1], 'mec': 'k', 'ms': markersize/1.1} for _ in locs_apic + locs_sb]
    markers[ca_ind]['marker'] = 'v'
    plotargs = {'lw': lwidth / 1.3, 'c': 'DarkGrey'}
    sim_tree.plot2DMorphology(axes_morph[0],
                              use_radius=False,
                              plotargs=plotargs,
                              marklocs=plocs,
                              locargs=markers,
                              lims_margin=0.01)
    # compartment tree dendrogram
    labelargs = {
        0: {
            'marker': 's',
            'mfc': cfl[0],
            'mec': 'k',
            'ms': markersize * 1.2
        }
    }
    labelargs.update({
        ii: {
            'marker': 's',
            'mfc': cfl[1],
            'mec': 'k',
            'ms': markersize * 1.2
        }
        for ii in range(1, len(plocs))
    })
    ctree.plotDendrogram(axes_morph[1],
                         plotargs={
                             'c': 'k',
                             'lw': lwidth
                         },
                         labelargs=labelargs)

    pl.show()
Beispiel #8
0
def basalAPBackProp(recompute_ctree=False, recompute_biophys=False, axes=None, pshow=True):
    global STIM_PARAMS, D2S_BASAL, SLOCS
    global CMAP_MORPH

    rc, rb  = recompute_ctree, recompute_biophys

    if axes is None:
        pl.figure(figsize=(7,5))
        ax1, ax2, ax4, ax5 = pl.subplot(221), pl.subplot(223), pl.subplot(222), pl.subplot(224)
        divider = make_axes_locatable(ax1)
        ax3 =  divider.append_axes("top", "30%", pad="10%")
        ax4, ax5 = myAx(ax4), myAx(ax5)
        pl.figure(figsize=(5,5))
        gs = GridSpec(2,2)
        ax_morph, ax_red1, ax_red2 = pl.subplot(gs[:,0]), pl.subplot(gs[1,0]), pl.subplot(gs[1,1])
    else:
        ax1, ax2, ax3 = axes['trace']
        ax4, ax5 = axes['amp-delay']
        ax_morph, ax_red1, ax_red2 = axes['morph']
        pshow = False

    # create the full model
    phys_tree = getL23PyramidNaK()
    sim_tree = phys_tree.__copy__(new_tree=NeuronSimTree())

    # distribute locations to measure backAPs on branches
    leafs_basal = [node for node in sim_tree.leafs if node.swc_type == 3]
    branches    = [sim_tree.pathToRoot(leaf)[::-1] for leaf in leafs_basal]
    locslist    = [sim_tree.distributeLocsOnNodes(D2S_BASAL, node_arg=branch) for branch in branches]
    branchlist  = [b for ii, b in enumerate(branches) if len(locslist[ii]) == 3]
    locs    = [locs for locs in locslist if len(locs) == 3][1]
    # do back prop sims
    amp_diffs_3loc, delay_diffs_3loc = np.zeros(3), np.zeros(3)
    amp_diffs_1loc, delay_diffs_1loc = np.zeros(3), np.zeros(3)
    amp_diffs_biop, delay_diffs_biop = np.zeros(3), np.zeros(3)

    # compartmentfitter object
    cfit = CompartmentFitter(phys_tree, name='basal_bAP', path='data/')

    # create reduced tree
    ctree, clocs = getCTree(cfit, [SLOCS[0]] + locs, 'data/ctree_basal_bAP_3loc',
                            recompute_ctree=rc, recompute_biophys=rb)
    csimtree = createReducedNeuronModel(ctree)
    print(ctree)

    # run the simulation of he full tree
    res = runSim(sim_tree, locs, SLOCS[0], stim_params=STIM_PARAMS)
    calcAmpDelayWidth(res)

    amp_diffs_biop[:] = res['amp'][1:]
    delay_diffs_biop[:] = res['delay'][1:]

    # run the simulation of the reduced tree
    cres = runSim(csimtree, clocs[1:], clocs[0], stim_params=STIM_PARAMS)
    calcAmpDelayWidth(cres)

    amp_diffs_3loc[:] = cres['amp'][1:]
    delay_diffs_3loc[:] = cres['delay'][1:]

    # reduced models with one single dendritic site
    creslist = []
    for jj, loc in enumerate(locs):
        # create reduced tree with all 1 single dendritic site locs
        ctree, clocs = getCTree(cfit, [SLOCS[0]] + [loc], 'data/ctree_basal_bAP_1loc%d'%jj,
                                recompute_ctree=rc, recompute_biophys=False)
        csimtree = createReducedNeuronModel(ctree)
        print(ctree)

        # run the simulation of the reduced tree
        cres_ss = runSim(csimtree, [clocs[1]], clocs[0], stim_params=STIM_PARAMS)
        calcAmpDelayWidth(cres_ss)
        creslist.append(cres_ss)

        amp_diffs_1loc[jj] = cres_ss['amp'][1]
        delay_diffs_1loc[jj] = cres_ss['delay'][1]


    ylim = (-90., 60.)
    x_range = np.array([-3.,14])
    xlim = (0., 12.)

    tp_full = res['t'][np.argmax(res['v_m'][0])]
    tp_3comp = cres['t'][np.argmax(cres['v_m'][0])]
    tp_1comp = creslist[2]['t'][np.argmax(creslist[2]['v_m'][0])]

    tlim_full = tp_full + x_range
    tlim_3comp = tp_3comp + x_range
    tlim_1comp = tp_1comp + x_range

    i0_full, i1_full = np.round(tlim_full / DT).astype(int)
    i0_3comp, i1_3comp = np.round(tlim_3comp / DT).astype(int)
    i0_1comp, i1_1comp = np.round(tlim_1comp / DT).astype(int)

    ax1.set_ylabel(r'soma')
    ax1.plot(res['t'][i0_full:i1_full] - tlim_full[0], res['v_m'][0][i0_full:i1_full],
             lw=lwidth, c='DarkGrey', label=r'full')
    ax1.plot(cres['t'][i0_3comp:i1_3comp] - tlim_3comp[0], cres['v_m'][0][i0_3comp:i1_3comp],
             ls='--', lw=1.6*lwidth, c=colours[0], label=r'3 comp')
    ax1.plot(creslist[2]['t'][i0_1comp:i1_1comp] - tlim_1comp[0], creslist[2]['v_m'][0][i0_1comp:i1_1comp],
             ls='-.', lw=1.6*lwidth, c=colours[1], label=r'1 comp')

    ax1.set_ylim(ylim)
    # ax1.set_xlim(xlim)
    drawScaleBars(ax1, b_offset=15)

    myLegend(ax1, add_frame=False, loc='center left', bbox_to_anchor=[0.35, 0.55], fontsize=ticksize,
                  labelspacing=.8, handlelength=2., handletextpad=.2)

    ax2.set_ylabel(r'dend' + '\n($d_{soma} = 150$ $\mu$m)')
    ax2.plot(res['t'][i0_full:i1_full] - tlim_full[0], res['v_m'][3][i0_full:i1_full],
             lw=lwidth, c='DarkGrey', label=r'full')
    ax2.plot(cres['t'][i0_3comp:i1_3comp] - tlim_3comp[0], cres['v_m'][3][i0_3comp:i1_3comp],
             ls='--', lw=1.6*lwidth, c=colours[0], label=r'3 comp')
    ax2.plot(creslist[2]['t'][i0_1comp:i1_1comp] - tlim_1comp[0], creslist[2]['v_m'][1][i0_1comp:i1_1comp],
             ls='-.', lw=1.6*lwidth, c=colours[1], label=r'1 comp')

    imax = np.argmax(res['v_m'][3])
    xp = res['t'][imax]

    ax2.annotate(r'$v_{amp}$',
                xy=(xlim[0], np.mean(ylim)), xytext=(xlim[0], np.mean(ylim)),
                fontsize=ticksize, ha='center', va='center', rotation=90.)
    ax2.annotate(r'$t_{delay}$',
                xy=(xp, ylim[1]), xytext=(xp, ylim[1]),
                fontsize=ticksize, ha='center', va='center', rotation=0.)

    ax2.set_ylim(ylim)
    ax2.set_xlim(xlim)

    drawScaleBars(ax2, xlabel=' ms', ylabel=' mV', b_offset=15)

    # myLegend(ax2, add_frame=False, ncol=2, fontsize=ticksize,
    #             loc='upper center', bbox_to_anchor=[.5, -.1],
    #             labelspacing=.6, handlelength=2., handletextpad=.2, columnspacing=.5)

    ax3.plot(res['t'][i0_full:i1_full] - tlim_full[0], -res['i_clamp'][0][i0_full:i1_full],
             lw=lwidth, c='r')
    ax3.set_yticks([0.,3.])
    drawScaleBars(ax3, ylabel=' nA', b_offset=0)
        # ax3.set_xlim(xlim)

    # color the branches
    cnodes = [b for branch in branches for b in branch]
    if cnodes is None:
        plotargs = {'lw': lwidth/1.3, 'c': 'DarkGrey'}
        cs = {node.index: 0 for node in sim_tree}
    else:
        plotargs = {'lw': lwidth/1.3}
        cinds = [n.index for n in cnodes]
        cs = {node.index: 1 if node.index in cinds else 0 for node in sim_tree}
    # mark example locations
    plocs = [SLOCS[0]] + locs
    markers = [{'marker': 's', 'c': cfl[0], 'mec': 'k', 'ms': markersize}] + \
              [{'marker': 's', 'c': cfl[1], 'mec': 'k', 'ms': markersize} for _ in plocs[1:]]
    # plot morphology
    sim_tree.plot2DMorphology(ax_morph, use_radius=False, plotargs=plotargs,
                                cs=cs, cmap=CMAP_MORPH,
                                marklocs=plocs, locargs=markers, lims_margin=0.01)

    # plot compartment tree schematic
    ctree_3l = cfit.setCTree([SLOCS[0]] + locs)
    ctree_3l = cfit.ctree
    ctree_1l = cfit.setCTree([SLOCS[0]] + locs[0:1])
    ctree_1l = cfit.ctree

    labelargs = {0: {'marker': 's', 'mfc': cfl[0], 'mec': 'k', 'ms': markersize*1.2}}
    labelargs.update({ii: {'marker': 's', 'mfc': cfl[1], 'mec': 'k', 'ms': markersize*1.2} for ii in range(1,len(plocs))})
    ctree_3l.plotDendrogram(ax_red1, plotargs={'c':'k', 'lw': lwidth}, labelargs=labelargs)

    labelargs = {0: {'marker': 's', 'mfc': cfl[0], 'mec': 'k', 'ms': markersize*1.2},
                 1: {'marker': 's', 'mfc': cfl[1], 'mec': 'k', 'ms': markersize*1.2}}
    ctree_1l.plotDendrogram(ax_red2, plotargs={'c':'k', 'lw': lwidth}, labelargs=labelargs)

    ax_red1.set_xticks([]); ax_red1.set_yticks([])
    ax_red1.set_xlabel(r'$\Delta x = 50$ $\mu$m', fontsize=ticksize,rotation=60)
    ax_red2.set_xticks([]); ax_red2.set_yticks([])
    ax_red2.set_xlabel(r'$\Delta x = 150$ $\mu$m', fontsize=ticksize,rotation=60)

    xb = np.arange(3)
    bwidth = 1./4.
    xtls = [r'50', r'100', r'150']

    ax4, ax5 = myAx(ax4), myAx(ax5)

    ax4.bar(xb-bwidth,        amp_diffs_biop,      width=bwidth, align='center', color='DarkGrey', edgecolor='k', label=r'full')
    ax4.bar(xb,               amp_diffs_3loc,      width=bwidth, align='center', color=colours[0], edgecolor='k', label=r'4 comp')
    ax4.bar((xb+bwidth)[-1:], amp_diffs_1loc[-1:], width=bwidth, align='center', color=colours[1], edgecolor='k', label=r'2 comp')

    ax4.set_ylabel(r'$v_{amp}$ (mV)')
    ax4.set_xticks(xb)
    ax4.set_xticklabels([])
    ax4.set_ylim(50.,110.)
    ax4.set_yticks([50., 80.])

    myLegend(ax4, add_frame=False, loc='lower center', bbox_to_anchor=[.5, 1.05], fontsize=ticksize,
                        labelspacing=.1, handlelength=1., handletextpad=.2, columnspacing=.5)

    ax5.bar(xb-bwidth,        delay_diffs_biop,      width=bwidth, align='center', color='DarkGrey', edgecolor='k', label=r'full')
    ax5.bar(xb,               delay_diffs_3loc,      width=bwidth, align='center', color=colours[0], edgecolor='k', label=r'4 comp')
    ax5.bar((xb+bwidth)[-1:], delay_diffs_1loc[-1:], width=bwidth, align='center', color=colours[1], edgecolor='k', label=r'2 comp')

    ax5.set_ylabel(r'$t_{delay}$ (ms)')
    ax5.set_xticks(xb)
    ax5.set_xticklabels(xtls)
    ax5.set_xlabel(r'$d_{soma}$ ($\mu$m)')
    ax5.set_yticks([0., 0.5])

    if pshow:
        pl.show()
def plotTrace(channel_names,
              zd,
              axes=None,
              plot_xlabel=True,
              plot_ylabel=True,
              plot_legend=True,
              units='uS/cm2',
              suffix='_predef'):
    ts = np.array([data.T0, data.T1, data.T2, data.T3]) - 100.
    pcolor = 'Orange' if zd else 'Blue'
    if units == 'uS/cm2':
        unit_conv = 1
    elif units == 'pS/um2':
        unit_conv = 0.01
    else:
        print('Unit type not defined, reverting to uS/cm2')
        unit_conv = 1

    # reduced trees
    full_tree, red_tree, full_locs, red_locs = data.reduceMorphology()
    sim_tree = red_tree.__copy__(new_tree=NeuronSimTree())
    # measured data
    v_dat = data.DataContainer(with_zd=zd)
    # get file name
    file_name = utils.getFileName(channel_names, zd, suffix=suffix)
    # model
    model_evaluator = optimizer.ModelEvaluator(sim_tree,
                                               v_dat,
                                               red_locs[0],
                                               red_locs[1],
                                               channel_names=channel_names)
    # load hall of fame
    file = open(file_name, 'rb')
    hall_of_fame = pickle.load(file)
    file.close()
    # run the best fit model
    model_evaluator.setParameterValues(hall_of_fame[0])
    print("\n--> running model for parameter values: \n%s" %
          model_evaluator.toStrParameterValues())
    res = model_evaluator.runSim()

    if axes is None:
        pl.figure('v opt', figsize=(16, 4))
        axes = [
            pl.subplot(161),
            pl.subplot(162),
            pl.subplot(163),
            pl.subplot(164),
            pl.subplot(165),
            pl.subplot(166)
        ]
        pshow = True
    else:
        pshow = False

    i0s = [int(tt / data.DT) for tt in ts]
    i1s = [int((tt + 1000. - data.DT) / data.DT) for tt in ts]
    t_plot = np.arange(0., 1000. - 3 * data.DT / 2., data.DT)

    pchanstr = r'' + ', '.join([PSTRINGS[c_name] for c_name in channel_names])
    ax = axes[0]
    # ax.set_title(pchanstr)
    ax.axison = False
    ax.text(0.,
            0.,
            pchanstr,
            horizontalalignment='center',
            verticalalignment='center',
            rotation=45.,
            fontsize=labelsize)
    ax.set_xlim((0., 1.))
    ax.set_ylim((-1., 1.))

    for ii in range(4):
        ax = noFrameAx(axes[ii + 1])
        i0, i1 = i0s[ii], i1s[ii]
        # plot traces
        ax.plot(t_plot,
                v_dat.v_s[i0:i1],
                c='k',
                lw=lwidth,
                label=r'$Exp_{soma}$')
        ax.plot(t_plot,
                v_dat.v_d[i0:i1],
                c=pcolor,
                lw=lwidth,
                label=r'$Exp_{dend}$')
        ax.plot(t_plot,
                res['v_m'][0][i0:i1],
                c='k',
                lw=2 * lwidth,
                alpha=.4,
                label=r'$Sim_{soma}$')
        ax.plot(t_plot,
                res['v_m'][1][i0:i1],
                c=pcolor,
                lw=2 * lwidth,
                alpha=.4,
                label=r'$Sim_{soma}$')

        if zd:
            ax.set_ylim((-110., -50.))
        else:
            ax.set_ylim((-95., -50.))

        if ii == 0:
            if not zd:
                ax.set_yticks([-65., -70.])
                ax.set_yticklabels(['-65 mV', '-70 mV'])
            else:
                ax.set_yticks([-75., -80.])
                ax.set_yticklabels(['-75 mV', '-80 mV'])

        if ii == 3 and plot_legend:
            myLegend(ax)
            # draw x scalebar
            ypos = ax.get_ylim()[0]
            xpos = ax.get_xlim()[-1] - 40.
            sblen = 400.
            ax.plot([xpos - sblen, xpos], [ypos, ypos], 'k-', lw=2. * lwidth)
            ax.annotate(r'%.0f ms' % sblen,
                        xy=(xpos - sblen / 2., ypos),
                        xytext=(xpos - sblen / 2., ypos - 4.),
                        size=labelsize,
                        rotation=0,
                        ha='center',
                        va='center')
            # draw y scalebar
            ypos = ax.get_ylim()[0] + 5.
            xpos = ax.get_xlim()[-1]
            sblen = 10.
            ax.plot([xpos, xpos], [ypos, ypos + sblen], 'k-', lw=2. * lwidth)
            ax.annotate(r'%.0f mV' % sblen,
                        xy=(xpos, ypos + sblen / 2.),
                        xytext=(xpos + 100., ypos + sblen / 2.),
                        size=labelsize,
                        rotation=90,
                        ha='center',
                        va='center')

    ax = myAx(axes[5])
    print('>>> parameters')
    for jj, pvals in enumerate(hall_of_fame):
        model_evaluator.setParameterValues(pvals)
        ps = model_evaluator.getParameterValuesAsDict()
        print(model_evaluator.toStrParameterValues())
        d2s = np.linspace(0., 400., int(1e3))
        for ii, c_name in enumerate(model_evaluator.channel_names):
            func = utils.expDistr(ps['d_' + c_name],
                                  ps['g0_' + c_name],
                                  g_max=model_evaluator.g_max[c_name])
            if jj == 0:
                ax.plot(d2s,
                        func(d2s) * unit_conv,
                        c=PCOLORS[c_name],
                        lw=lwidth,
                        label=PSTRINGS[c_name])
            else:
                ax.plot(d2s,
                        func(d2s) * unit_conv,
                        c=PCOLORS[c_name],
                        lw=3. * lwidth,
                        alpha=.07)
    if plot_legend:
        myLegend(ax)
    if plot_xlabel:
        ax.set_xlabel(r'Distance ($\mu$m)', fontsize=labelsize)
    else:
        ax.set_xticklabels([])
    if plot_ylabel:
        if units == 'pS/um2':
            ax.set_ylabel(r'Conductance (pS/$\mu$m$^2$)', fontsize=labelsize)
        else:
            ax.set_ylabel(r'Conductance ($\mu$S/cm$^2$)', fontsize=labelsize)
    if zd:
        ax.set_ylim((0., 2000. * unit_conv))
        ax.set_yticks([0., 1000. * unit_conv])
    else:
        ax.set_ylim((0., 6000. * unit_conv))
        ax.set_yticks([0., 3000. * unit_conv])

    if pshow:
        pl.tight_layout()
        pl.show()
def plotErrors(channel_names_list,
               zd_list,
               ax=None,
               qs=[.01, .5, .99],
               suffix='_predef'):
    global PSTRINGS

    full_tree, red_tree, full_locs, red_locs = data.reduceMorphology()
    sim_tree = red_tree.__copy__(new_tree=NeuronSimTree())

    v_qmins, v_meds, v_qmaxs = [], [], []
    ticklabels = []
    for channel_names, zd in zip(channel_names_list, zd_list):

        # load hall of fame
        file_name = utils.getFileName(channel_names, zd, suffix=suffix)
        file = open(file_name, 'rb')
        hall_of_fame = pickle.load(file)
        file.close()

        # measured data
        v_dat = data.DataContainer(with_zd=zd)

        # model
        model_evaluator = optimizer.ModelEvaluator(sim_tree,
                                                   v_dat,
                                                   red_locs[0],
                                                   red_locs[1],
                                                   channel_names=channel_names)

        # compute the errors
        v_errs = calcError(model_evaluator, hall_of_fame, v_dat)

        # compute quantiles
        v_qmin, v_med, v_qmax = np.quantile(v_errs, qs)
        v_qmins.append(v_qmin)
        v_meds.append(v_med)
        v_qmaxs.append(v_qmax)

        # tick label for this configuration
        tl = r'' + ', '.join([PSTRINGS[c_name] for c_name in channel_names])
        ticklabels.append(tl)

    v_meds = np.array(v_meds)
    v_errs = np.abs(np.array([v_qmins, v_qmaxs]) - v_meds[None, :])
    inds_h = np.where(np.logical_not(np.array(zd_list)))[0]
    inds_zd = np.where(np.array(zd_list))[0]
    n_h = len(inds_h)
    n_zd = len(inds_zd)
    ticklabels = [ticklabels[ii] for ii in inds_h]

    print(v_errs)

    if ax is None:
        pl.figure('v errors')
        ax = pl.gca()
        pshow = True
    else:
        pshow = False

    if n_h > 0:
        ax.bar(np.arange(n_h),
               v_meds[inds_h],
               width=.3,
               align='edge',
               yerr=v_errs[:, inds_h],
               color='Blue')
    if n_zd > 0:
        ax.bar(np.arange(n_zd),
               v_meds[inds_zd],
               width=-.3,
               align='edge',
               yerr=v_errs[:, inds_zd],
               color='Orange')

    ax.set_xticks(np.arange(np.max([n_zd, n_h])))
    ax.set_xticklabels(ticklabels, rotation=60., fontsize=labelsize)
    ax.set_ylabel(r'$V_{error}$ (mV)')

    if pshow:
        pl.show()
Beispiel #11
0
class TestNeuron():
    def loadTTreePassive(self):
        """
        Load the T-tree morphology in memory with passive conductance

          6--5--4--7--8
                |
                |
                1
        """
        v_eq = -75.
        self.dt = 0.025
        self.tmax = 100.
        # for frequency derivation
        self.ft = ke.FourrierTools(np.arange(0., self.tmax, self.dt))
        # load the morphology
        fname = os.path.join(MORPHOLOGIES_PATH_PREFIX, 'Tsovtree.swc')
        self.greenstree = GreensTree(fname, types=[1, 3, 4])
        self.greenstree.fitLeakCurrent(v_eq, 10.)
        self.greenstree.setCompTree()
        self.greenstree.setImpedance(self.ft.s)
        # copy greenstree parameters into NEURON simulation tree
        self.neurontree = NeuronSimTree(dt=self.dt,
                                        t_calibrate=10.,
                                        v_init=v_eq,
                                        factor_lambda=25.)
        self.greenstree.__copy__(self.neurontree)
        self.neurontree.treetype = 'computational'

    def loadTTreeActive(self):
        """
        Load the T-tree morphology in memory with h-current

          6--5--4--7--8
                |
                |
                1
        """
        v_eq = -75.
        self.dt = 0.1
        self.tmax = 100.
        # for frequency derivation
        self.ft = ke.FourrierTools(np.arange(0., self.tmax, self.dt))
        # load the morphology
        h_chan = channelcollection.h()
        fname = os.path.join(MORPHOLOGIES_PATH_PREFIX, 'Tsovtree.swc')
        self.greenstree = GreensTree(fname, types=[1, 3, 4])
        self.greenstree.addCurrent(h_chan, 50., -43.)
        self.greenstree.fitLeakCurrent(v_eq, 10.)
        self.greenstree.setCompTree()
        self.greenstree.setImpedance(self.ft.s)
        # copy greenstree parameters into NEURON simulation tree
        self.neurontree = NeuronSimTree(dt=self.dt,
                                        t_calibrate=10.,
                                        v_init=v_eq,
                                        factor_lambda=25.)
        self.greenstree.__copy__(self.neurontree)
        self.neurontree.treetype = 'computational'

    def loadTTreeTestChannel(self):
        """
        Load the T-tree morphology in memory with h-current

          6--5--4--7--8
                |
                |
                1
        """
        v_eq = -75.
        self.dt = 0.025
        self.tmax = 100.
        # for frequency derivation
        self.ft = ke.FourrierTools(np.arange(0., self.tmax, self.dt))
        # load the morphology
        test_chan = channelcollection.TestChannel2()
        fname = os.path.join(MORPHOLOGIES_PATH_PREFIX, 'Tsovtree.swc')
        self.greenstree = GreensTree(fname, types=[1, 3, 4])
        self.greenstree.addCurrent(test_chan, 50., -23.)
        self.greenstree.fitLeakCurrent(v_eq, 10.)
        self.greenstree.setCompTree()
        self.greenstree.setImpedance(self.ft.s)
        # copy greenstree parameters into NEURON simulation tree
        self.neurontree = NeuronSimTree(dt=self.dt,
                                        t_calibrate=100.,
                                        v_init=v_eq,
                                        factor_lambda=25.)
        self.greenstree.__copy__(self.neurontree)
        self.neurontree.treetype = 'computational'

    def loadTTreeTestChannelSoma(self):
        """
        Load the T-tree morphology in memory with h-current

          6--5--4--7--8
                |
                |
                1
        """
        v_eq = -75.
        self.dt = 0.025
        self.tmax = 100.
        # for frequency derivation
        self.ft = ke.FourrierTools(np.arange(0., self.tmax, self.dt))
        # load the morphology
        test_chan = channelcollection.TestChannel2()
        fname = os.path.join(MORPHOLOGIES_PATH_PREFIX, 'Tsovtree.swc')
        self.greenstree = GreensTree(fname, types=[1, 3, 4])
        self.greenstree.addCurrent(test_chan,
                                   50.,
                                   23.,
                                   node_arg=[self.greenstree[1]])
        self.greenstree.fitLeakCurrent(v_eq, 10.)
        self.greenstree.setCompTree()
        self.greenstree.setImpedance(self.ft.s)
        # copy greenstree parameters into NEURON simulation tree
        self.neurontree = NeuronSimTree(dt=self.dt,
                                        t_calibrate=100.,
                                        v_init=v_eq,
                                        factor_lambda=25.)
        self.greenstree.__copy__(self.neurontree)
        self.neurontree.treetype = 'computational'

    def testPassive(self, pplot=False):
        self.loadTTreePassive()
        # set of locations
        locs = [(1, .5), (4, .5), (4, 1.), (5, .5), (6, .5), (7, .5), (8, .5)]
        # compute impedance matrix with Green's function
        zf_mat_gf = self.greenstree.calcImpedanceMatrix(locs)
        z_mat_gf = zf_mat_gf[self.ft.ind_0s].real
        # convert impedance matrix to time domain
        zk_mat_gf = np.zeros((len(self.ft.t), len(locs), len(locs)))
        for (ii, jj) in itertools.product(list(range(len(locs))),
                                          list(range(len(locs)))):
            zk_mat_gf[:, ii,
                      jj] = self.ft.ftInv(zf_mat_gf[:, ii, jj])[1].real * 1e-3
        # test the steady state impedance matrix
        z_mat_neuron = self.neurontree.calcImpedanceMatrix(locs)
        assert np.allclose(z_mat_gf, z_mat_neuron, atol=1.)
        # test the temporal matrix
        tk, zk_mat_neuron = self.neurontree.calcImpedanceKernelMatrix(locs)
        assert np.allclose(zk_mat_gf[int(2. / self.dt):, :, :],
                           zk_mat_neuron[int(2. / self.dt):, :, :],
                           atol=.2)
        if pplot:
            # plot kernels
            pl.figure()
            cc = 0
            for ii in range(len(locs)):
                jj = 0
                while jj <= ii:
                    pl.plot(tk,
                            zk_mat_neuron[:, ii, jj],
                            c=colours[cc % len(colours)])
                    pl.plot(tk,
                            zk_mat_gf[:, ii, jj],
                            ls='--',
                            lw=2,
                            c=colours[cc % len(colours)])
                    cc += 1
                    jj += 1
            pl.show()

    def testActive(self, pplot=False):
        self.loadTTreeActive()
        # set of locations
        locs = [(1, .5), (4, .5), (6, .5), (7, .5), (8, .5)]
        # compute impedance matrix with Green's function
        zf_mat_gf = self.greenstree.calcImpedanceMatrix(locs)
        z_mat_gf = zf_mat_gf[self.ft.ind_0s].real
        # convert impedance matrix to time domain
        zk_mat_gf = np.zeros((len(self.ft.t), len(locs), len(locs)))
        for (ii, jj) in itertools.product(list(range(len(locs))),
                                          list(range(len(locs)))):
            zk_mat_gf[:, ii,
                      jj] = self.ft.ftInv(zf_mat_gf[:, ii, jj])[1].real * 1e-3
        # test the steady state impedance matrix
        z_mat_neuron = self.neurontree.calcImpedanceMatrix(locs, t_dur=500.)
        assert np.allclose(z_mat_gf, z_mat_neuron, atol=5.)
        # test the temporal matrix
        tk, zk_mat_neuron = self.neurontree.calcImpedanceKernelMatrix(locs)
        assert np.allclose(zk_mat_gf[int(2. / self.dt):, :, :],
                           zk_mat_neuron[int(2. / self.dt):, :, :],
                           atol=.5)
        if pplot:
            # plot kernels
            pl.figure()
            cc = 0
            for ii in range(len(locs)):
                jj = 0
                while jj <= ii:
                    pl.plot(tk,
                            zk_mat_neuron[:, ii, jj],
                            c=colours[cc % len(colours)])
                    pl.plot(tk,
                            zk_mat_gf[:, ii, jj],
                            ls='--',
                            lw=2,
                            c=colours[cc % len(colours)])
                    cc += 1
                    jj += 1
            pl.show()

    def testChannelRecording(self):
        self.loadTTreeTestChannel()
        # set of locations
        locs = [(1, .5), (4, .5), (4, 1.), (5, .5), (6, .5), (7, .5), (8, .5)]
        # create simulation tree
        self.neurontree.initModel(t_calibrate=10., factor_lambda=10.)
        self.neurontree.storeLocs(locs, name='rec locs')
        # run test simulation
        res = self.neurontree.run(1., record_from_channels=True)
        # check if results are stored correctly
        assert set(res['chan']['TestChannel2'].keys()) == {
            'a00', 'a01', 'a10', 'a11', 'p_open'
        }
        # check if values are correct
        assert np.allclose(res['chan']['TestChannel2']['a00'], .3)
        assert np.allclose(res['chan']['TestChannel2']['a01'], .5)
        assert np.allclose(res['chan']['TestChannel2']['a10'], .4)
        assert np.allclose(res['chan']['TestChannel2']['a11'], .6)
        assert np.allclose(res['chan']['TestChannel2']['p_open'],
                           .9 * .3**3 * .5**2 + .1 * .4**2 * .6**1)
        # check if shape is correct
        n_loc, n_step = len(locs), len(res['t'])
        assert res['chan']['TestChannel2']['a00'].shape == (n_loc, n_step)
        assert res['chan']['TestChannel2']['a01'].shape == (n_loc, n_step)
        assert res['chan']['TestChannel2']['a10'].shape == (n_loc, n_step)
        assert res['chan']['TestChannel2']['a11'].shape == (n_loc, n_step)
        assert res['chan']['TestChannel2']['p_open'].shape == (n_loc, n_step)
        # channel only at soma
        self.loadTTreeTestChannelSoma()
        # create simulation tree
        self.neurontree.initModel(t_calibrate=100., factor_lambda=10.)
        self.neurontree.storeLocs(locs, name='rec locs')
        # run test simulation
        res = self.neurontree.run(10., record_from_channels=True)
        # check if results are stored correctly
        assert set(res['chan']['TestChannel2'].keys()) == {
            'a00', 'a01', 'a10', 'a11', 'p_open'
        }
        # check if values are correct
        assert np.allclose(res['chan']['TestChannel2']['a00'][0, :], .3)
        assert np.allclose(res['chan']['TestChannel2']['a01'][0, :], .5)
        assert np.allclose(res['chan']['TestChannel2']['a10'][0, :], .4)
        assert np.allclose(res['chan']['TestChannel2']['a11'][0, :], .6)
        assert np.allclose(res['chan']['TestChannel2']['p_open'][0, :],
                           .9 * .3**3 * .5**2 + .1 * .4**2 * .6**1)
        assert np.allclose(res['chan']['TestChannel2']['a00'][1:, :], 0.)
        assert np.allclose(res['chan']['TestChannel2']['a01'][1:, :], 0.)
        assert np.allclose(res['chan']['TestChannel2']['a10'][1:, :], 0.)
        assert np.allclose(res['chan']['TestChannel2']['a11'][1:, :], 0.)
        assert np.allclose(res['chan']['TestChannel2']['p_open'][1:, :], 0.)
        # check if shape is correct
        n_loc, n_step = len(locs), len(res['t'])
        assert res['chan']['TestChannel2']['a00'].shape == (n_loc, n_step)
        assert res['chan']['TestChannel2']['a01'].shape == (n_loc, n_step)
        assert res['chan']['TestChannel2']['a10'].shape == (n_loc, n_step)
        assert res['chan']['TestChannel2']['a11'].shape == (n_loc, n_step)
        assert res['chan']['TestChannel2']['p_open'].shape == (n_loc, n_step)