Exemplo n.º 1
0
    def _get_neuron(self, key):
        try:
            params = IzhikevichDemo.parameters[key]
        except KeyError as e:
            print((' %s : Invalid neuron type. The valid types are:' % (key)))
            for key in IzhikevichDemo.parameters:
                print(key)
            raise e
        try:
            neuron = self.neurons[key]
            return neuron
        except KeyError as e:
            neuron = moose.IzhikevichNrn(self.model_container.path + '/' + key)

        if key == 'integrator' or key == 'Class_1': # Integrator has different constants
            neuron.beta = 4.1e3
            neuron.gamma = 108.0
        if key == 'accommodation':
            neuron.accommodating = True
            neuron.u0 = -0.065
        self.neuron = neuron
        neuron.a = params[1] * 1e3 # ms^-1 -> s^-1
        neuron.b = params[2] * 1e3 # ms^-1 -> s^-1
        neuron.c = params[3] * 1e-3 # mV -> V
        neuron.d = params[4]  # d is in mV/ms = V/s
        neuron.initVm = params[6] * 1e-3 # mV -> V
        neuron.Vmax = 0.03 # mV -> V
        if key != 'accommodation':
            neuron.initU = neuron.initVm * neuron.b
        else:
            neuron.initU = -16.0 # u is in mV/ms = V/s
            moose.showfield(neuron)
        self.neurons[key] = neuron
        return neuron
Exemplo n.º 2
0
def library1():
    import moose.genesis
    import moose.SBML
    import moose.chemMerge
    import moose.utils
    import moose.network_utils
    print('done')

    p1 = moose.le()
    a = moose.Pool('/a')
    for i in range(10):
        moose.Pool('/a/p%d' % i)
    p2 = moose.le()
    assert set(p2) - set(p1) == set(['/a'])
    aa = moose.le(a)
    assert len(aa) == 10

    try:
        moose.syncDataHandler('/a')
    except NotImplementedError:
        pass

    try:
        moose.showfield('/x')
    except ValueError:
        pass

    moose.showfield('/a')
    moose.showfields('/a')
Exemplo n.º 3
0
    def _get_neuron(self, key):
        try:
            params = IzhikevichDemo.parameters[key]
        except KeyError as e:
            print((' %s : Invalid neuron type. The valid types are:' % (key)))
            for key in IzhikevichDemo.parameters:
                print(key)
            raise e
        try:
            neuron = self.neurons[key]
            return neuron
        except KeyError as e:
            neuron = moose.IzhikevichNrn(self.model_container.path + '/' + key)

        if key == 'integrator' or key == 'Class_1': # Integrator has different constants
            neuron.beta = 4.1e3
            neuron.gamma = 108.0
        if key == 'accommodation':
            neuron.accommodating = True
            neuron.u0 = -0.065
        self.neuron = neuron
        neuron.a = params[1] * 1e3 # ms^-1 -> s^-1
        neuron.b = params[2] * 1e3 # ms^-1 -> s^-1
        neuron.c = params[3] * 1e-3 # mV -> V
        neuron.d = params[4]  # d is in mV/ms = V/s
        neuron.initVm = params[6] * 1e-3 # mV -> V
        neuron.Vmax = 0.03 # mV -> V
        if key != 'accommodation':
            neuron.initU = neuron.initVm * neuron.b
        else:
            neuron.initU = -16.0 # u is in mV/ms = V/s
            moose.showfield(neuron)
        self.neurons[key] = neuron
        return neuron
def create_compartment(path):
    comp = moose.Compartment(path)
    comp.diameter = soma_dia
    comp.Em = EREST_ACT + 10.613e-3
    comp.initVm = EREST_ACT
    sarea = np.pi * soma_dia * soma_dia
    comp.Rm = 1/(0.3e-3 * 1e4 * sarea)
    comp.Cm = 1e-6 * 1e4 * sarea
    if moose.exists('/library/na'):
        nachan = moose.element(moose.copy('/library/na', comp, 'na'))
    else:
        nachan = create_na_chan(comp.path)
    nachan.Gbar = 120e-3 * sarea * 1e4
    moose.showfield(nachan)
    moose.connect(nachan, 'channel', comp, 'channel')
    if moose.exists('/library/k'):
        kchan = moose.element(moose.copy('/library/k', comp, 'k'))
    else:
        kchan = create_k_chan(comp.path)
    kchan.Gbar = 36e-3 * sarea * 1e4
    moose.connect(kchan, 'channel', comp, 'channel')
    synchan = moose.SynChan(comp.path + '/synchan')
    synchan.Gbar = 1e-8
    synchan.tau1 = 2e-3
    synchan.tau2 = 2e-3
    synchan.Ek = 0.0
    m = moose.connect(comp, 'channel', synchan, 'channel')
    spikegen = moose.SpikeGen(comp.path + '/spikegen')
    spikegen.threshold = 0.0
    m = moose.connect(comp, 'VmOut', spikegen, 'Vm')
    return comp
Exemplo n.º 5
0
def test_showfield_func():
    """Show field of a function.
    >>> test_showfield_func()   #doctest: +NORMALIZE_WHITESPACE
    [/dadada[0]]
    allowUnknownVariable    =True
    className               =Function
    derivative              =nan
    doEvalAtReinit          =False
    dt                      =0.1
    expr                    =0
    fieldIndex              =0
    idValue                 =448
    independent             =t
    index                   =0
    mode                    =1
    name                    =dadada
    numData                 =1
    numField                =1
    numVars                 =0
    path                    =/dadada[0]
    rate                    =0.0
    tick                    =12
    useTrigger              =False
    value                   =0.0
    """
    f = moose.Function('/dadada')
    moose.showfield(f)
Exemplo n.º 6
0
def main():
    library = moose.Neutral('/library')
    makePassiveSoma('cell', params['dendL'], params['dendDia'])
    makeChemProto()
    rdes = rd.rdesigneur(
        turnOffElec=True,
        chemPlotDt=0.1,
        diffusionLength=params['diffusionL'],
        cellProto=[['cell', 'soma']],
        chemProto=[['hydra', 'hydra']],
        chemDistrib=[['hydra', 'soma', 'install', '1']],
        plotList=[['soma', '1', 'dend/A', 'n', '# of A'],
                  ['soma', '1', 'dend/B', 'n', '# of B']],
        #    moogList = [['soma', '1', 'dend/A', 'n', 'num of A (number)']]
    )
    moose.le('/library')
    moose.le('/library/hydra')
    moose.showfield('/library/soma/soma')
    rdes.buildModel()
    #moose.element('/model/chem/dend/B').vec[50].nInit=15.5

    A = moose.vec('/model/chem/dend/A')
    #B = moose.vec('/model/chem/dend/B')
    #    A.concInit=1
    #    B.concInit=10
    moose.element('/model/chem/dend/B').vec[50].nInit = 100
    #moose.element('/model/chem/dend/B').vec[25].nInit=0
    #A.nInit=1
    #B.nInit=15

    #Adot = moose.element('/model/chem/dend/A/Adot')
    #Bdot = moose.element('/model/chem/dend/B/Bdot')

    #print "\n\n\t\t Before Run", Adot, Bdot, A.nInit, B.nInit, A.n, B.n, A.concInit, B.concInit

    moose.reinit()
    moose.start(500)

    #print "\n\n\t\t After Run", A.nInit, B.nInit, A.n, B.n, A.concInit, B.concInit

    # rdes.display()
    # rdes.displayMoogli( 1, 400, 0.001 )
    avec = moose.vec('/model/chem/dend/A').n
    bvec = moose.vec('/model/chem/dend/B').n
    #tab = moose.element( '/model/graphs/plot0')
    #dt = tab.dt
    #tvec=[]
    #tvec.append( tab.vector )
    # xplot = []
    # xplot.append( avec )
    ##  t = np.arange( 0, len( tvec[0] ), 1.0 ) * dt
    plt.plot(avec)

    #print bvec, len(bvec), bvec

    return bvec, avec
Exemplo n.º 7
0
def insert_ca(compartment, phi, tau):
    ca = moose.copy(CaPool.prototype, compartment)[0]
    ca.B = phi / (np.pi * compartment.length * compartment.diameter)
    ca.tau = tau
    print ca.path, ca.B, ca.tau
    for chan in moose.wildcardFind('%s/#[TYPE=HHChannel]' % (compartment.path)):
        if chan.name.startswith('KC') or chan.name.startswith('KAHP'):
            moose.connect(ca, 'concOut', chan, 'concen')
        elif chan.name.startswith('CaL'):
            moose.connect(chan, 'IkOut', ca, 'current')
        else:
            continue
        moose.showfield(chan)
    return ca
Exemplo n.º 8
0
def insert_ca(compartment, phi, tau):
    ca = moose.copy(CaPool.prototype, compartment)[0]
    ca.B = phi / (np.pi * compartment.length * compartment.diameter)
    ca.tau = tau
    print ca.path, ca.B, ca.tau
    for chan in moose.wildcardFind('%s/#[TYPE=HHChannel]' %
                                   (compartment.path)):
        if chan.name.startswith('KC') or chan.name.startswith('KAHP'):
            moose.connect(ca, 'concOut', chan, 'concen')
        elif chan.name.startswith('CaL'):
            moose.connect(chan, 'IkOut', ca, 'current')
        else:
            continue
        moose.showfield(chan)
    return ca
Exemplo n.º 9
0
def create_1comp_neuron(path, number=1):
    """Create single-compartmental neuron with Na+ and K+ channels.

    Parameters
    ----------
    path : str
        path of the compartment to be created

    number : int
        number of compartments to be created. If n is greater than 1,
        we create a vec with that size, each having the same property.

    Returns
    -------
    comp : moose.Compartment
        a compartment vec with `number` elements.

    """
    comps = moose.vec(path=path, n=number, dtype='Compartment')
    diameter = 30e-6
    length = 50e-6
    sarea = np.pi * diameter * length
    xarea = np.pi * diameter * diameter / 4.0
    Em = EREST_ACT + 10.613e-3
    comps.Em = Em
    comps.initVm = EREST_ACT
    #: CM = 1 uF/cm^2
    comps.Cm = 1e-6 * sarea * 1e4
    #: RM = 0.3 mS/cm^2
    comps.Rm = 1 / (0.3e-3 * sarea * 1e4)
    container = comps[0].parent.path
    #: Here we create copies of the prototype channels
    nachan = moose.copy(create_na_proto(), container, 'na', number)
    #: Gbar_Na = 120 mS/cm^2
    nachan.Gbar = 120e-3 * sarea * 1e4
    nachan.Ek = 115e-3 + EREST_ACT
    moose.showfield(nachan.path)
    moose.connect(nachan, 'channel', comps, 'channel', 'OneToOne')
    kchan = moose.copy(create_k_proto(), container, 'k', number)

    #: Gbar_K = 36 mS/cm^2
    kchan.Gbar = 36e-3 * sarea * 1e4
    kchan.Ek = -12e-3 + EREST_ACT
    moose.showfield(kchan.path)
    moose.connect(kchan, 'channel', comps, 'channel', 'OneToOne')
    return comps
Exemplo n.º 10
0
def test_simple():
    """First test.
    >>> test_simple() # doctest: +NORMALIZE_WHITESPACE
    Rdesigneur: Elec model has 1 compartments and 0 spines on 0 compartments.
    <BLANKLINE>
    [/model[0]/elec[0]/soma[0]]
    Cm              =7.853981633975e-09
    Em              =-0.0544
    Im              =1.3194689277024895e-08
    Ra              =7639437.268410473
    Rm              =424413.1773342278
    Vm              =-0.06
    className       =ZombieCompartment
    diameter        =0.0005
    dt              =0.0
    fieldIndex      =0
    idValue         =455
    index           =0
    initVm          =-0.065
    inject          =0.0
    length          =0.0005
    name            =soma
    numData         =1
    numField        =1
    path            =/model[0]/elec[0]/soma[0]
    tick            =-2
    x               =0.0005
    x0              =0.0
    y               =0.0
    y0              =0.0
    z               =0.0
    z0              =0.0
    <BLANKLINE>
    INCOMING:
    /model[0]/elec[0]/soma ('parentMsg',) <--- /model[0]/elec ('childOut',)                                         
    OUTGOING:
    """
    rdes = rd.rdesigneur()
    rdes.buildModel()
    moose.showfield(rdes.soma)
    moose.showmsg(rdes.soma)
Exemplo n.º 11
0
def addChannelToComps(channelSpecs, comps, number=1):
    container = comps[0].parent.path
    protoChannel = create_channel_proto(channelSpecs["settings"])
    print(container)
    print(protoChannel)
    channel = moose.copy(protoChannel, container, channelSpecs["settings"].name+'_{}'.format(comps.name), number)
    channel.Gbar = channelSpecs["gbar"] * np.pi*comps.length*comps.diameter # is the list unnecessary?
    channel.Ek = channelSpecs["Ek"]
    print(moose.showfield(moose.element(channel)))
    moose.connect(channel, "channel", comps, "channel", "OneToOne")
    if(channelSpecs["settings"].chan_type!=""):
        print(channelSpecs["settings"].chan_type)
        add_calcium(channel.name, Ca_pool_settings, channel.name, channelSpecs["settings"].chan_type, 'CaPool')
    return channel
Exemplo n.º 12
0
moose.reinit()

# start simulation at 0 nA injection current.
moose.start(0.3)
moose.showfields(soma)  # check Vm

soma.inject = -1E-12
# reset simulation
moose.reint()
# start simulation at -1pA injection current.
moose.start(0.3)
moose.showfields(soma)

# Creation of pulse generator.
pulse = moose.PulseGen('pulse')
moose.showfield('pulse')
pulse.delay[0] = 50E-3  # First delay.
pulse.width[0] = 100E03  # Pulse width.
pulse.level[0] = 1E-9  # Pulse amplitude.
pulse.delat[1] = 1E9

moose.getFieldNames(
    'PulseGen',
    'srcFinfo')  # returns list of message outlets for a moose element class.
moose.getFieldNames(
    'Compartment',
    'destFinfo')  # returns list of message inlets for a moose element class.
soma.getFieldNames('destFinfo')
moose.showmsg(
    'soma')  # shows  message connetions statistics of the moose element.
Exemplo n.º 13
0
    moose.reinit()
    moose.start(900e-3)


neuron = moose.Neutral("/neuron")
inputs = moose.Neutral("/inputs")
outputs = moose.Neutral("/outputs")

swcNeuron = load_neuron_file("538ser3sl5-cell1-2-a.CNG.swc", "/swcNeuron", 0.8,
                             0.9, 0.01, 0.072)
moose.le("/swcNeuron")

pulse = create_pulse("/inputs/somaPulse", 10e-3, 10e-3, 0.1e-9,
                     moose.element("/swcNeuron/soma"))
table = create_table('outputs/somaVmTable', moose.element("/swcNeuron/soma"),
                     "getVm")
dtable = create_table('outputs/dendVmTable',
                      moose.element("/swcNeuron/dend_3_0"), "getVm")

run_sim()

plot_tables([table, dtable])
pyplot.show()

ch = moose.HHChannel("ch")
moose.showfield(ch)
ch.Xpower = 3
ch.Ypower = 1
ch.Ek = 0.05
ch.Gbar = 1
Exemplo n.º 14
0
def main():
    """
    This illustrates the use of rdesigneur to build a simple dendrite with
    spines, and then to resize them using spine fields. These are the
    fields that would be changed dynamically in a simulation with reactions
    that affect spine geometry.
    In this simulation there is a propagating reaction wave using a
    highly abstracted equation, whose product diffuses into the spines and
    makes them bigger.
    """
    radCalc()
    moose.delete('/model')
    makeModel()
    for i in range(11, 18):
        moose.setClock(i, 0.01)
    moose.setClock(18, 0.01)
    elec = moose.element('/model/elec')
    graphs = moose.Neutral('/graphs')
    Epsinit = moose.vec('/model/chem/dend/Eps8')
    Cdcinit = moose.vec('/model/chem/dend/Cdc42')
    IRSpinit = moose.vec('/model/chem/dend/IRSp53')
    PIPinit = moose.vec('/model/chem/dend/PIP2')
    Cdcinit.concInit = 0.0
    ##    Cdcinit[100].concInit=0.01
    ##Epsinit.concInit=0.0
    ##Epsinit[50].concInit=0.010

    ###    IRSpinit.nInit=0.0
    for ci in range(90, 110):
        Cdcinit[ci].concInit = np.exp(-(
            (ci - 100)**2) / 10.**2) * 0.005 + 0.005
##        Cdcinit[ci].concInit=0.010
    PIPinit.nInit = 565

    print moose.vec('/model/chem/dend/Cdc42').nInit
    print moose.vec('/model/chem/dend/IRSp53').nInit
    makePlot('IRSp53', moose.vec('/model/chem/dend/IRSp53'), 'getN')
    makePlot('height', moose.vec('/model/chem/dend/height'), 'getN')
    makePlot('IM', moose.vec('/model/chem/dend/IRSp53_m'), 'getN')
    makePlot('Rad', moose.vec('/model/chem/dend/Rad'), 'getN')
    makePlot('curv_IRSp53', moose.vec('/model/chem/dend/curv_IRSp53'), 'getN')
    makePlot('Ipool', moose.vec('/model/chem/dend/Ipool'), 'getN')
    makePlot('sort', moose.vec('/model/chem/dend/sort'), 'getN')
    rad = moose.element('/model/chem/dend/Rad')
    ##curv[gri]=(radv[gri+1]-2*radv[gri]+radv[gri-1])/(200*200*1e-9)
    ##   curv[gric]=1e-9*(heightvec[gric+1]-2*heightvec[gric]+heightvec[gric-1])/(0.2*0.2*1e-12)
    mypyrun = moose.PyRun('/model/mypyrun')
    ##    curv[gri]=np.exp(6*curv_IRSp53vec[gri]+6*cip2vec[gri]+6*cip3vec[gri]+2*IRSp53_mvec[gri])
    ##cPIP2.diffConst=abs(0.33e-12-(1.0/np.exp(abs(max(radv)*1e9-20.)))*0.33e-12)
    ##curv_IRSp53.diffConst=cPIP2.diffConst
    ##curv[gric]=1e-9*(-heightvec[gric+2]+16*heightvec[gric+1]-30*heightvec[gric]+16*heightvec[gric-1]-heightvec[gric-2])/(12*20.0*20.0*1e-18)
    ###curv[gric]=1e-9*(-radv[gric+2]+16*radv[gric+1]-30*radv[gric]+16*radv[gric-1]-radv[gric-2])/(12*50.0*50.0*1e-18)
    ##curv[gric]=1e-9*(radv[gric+1]-2*radv[gric]+radv[gric-1])/(0.05*0.05*1e-12)
    ##for gric in range(0,len(curv)):
    ##   curv[gric]=1.0/(100.0-2*1e9*radv[gric])
    ##   curv[gric]=curv[gric]

    ##   curv[gri].conc=(3*27000*IRSp53_mvec[gri].conc**2)/(1+3*27000*IRSp53_mvec[gri].conc**2)
    ##   curv[gri]=1030*((3*0.027*(3*curv_IRSp53vec[gri]+3*cip2vec[gri]+3*cip3vec[gri]+IRSp53_mvec[gri])**2)/(1.0+3.0*0.027*(3.0*curv_IRSp53vec[gri]+3.0*cip2vec[gri]+3.0*cip3vec[gri]+IRSp53_mvec[gri])**2))
    print moose.showfield('/model/chem/dend/curv/Enz'), 'number of substrates'
    mypyrun.initString = """count=0"""
    mypyrun.runString = """count=count+1
radv=moose.vec('/model/chem/dend/Rad').n
radm=radv[10]
output=radm
IRvec=moose.vec( '/model/chem/dend/IRSp53' ).n
curv_IRSp53=moose.element( '/model/chem/dend/curv_IRSp53')
Cdcvec=moose.vec( '/model/chem/dend/Cdc42' ).n
if count==1:
    Cdcinit=moose.vec( '/model/chem/dend/Cdc42' ).nInit
    pos=np.unravel_index(np.argmax(Cdcinit), Cdcinit.shape)
    pos=pos[0]
heightvec=moose.vec( '/model/chem/dend/height' ).n
curv_IRSp53vec=moose.vec('/model/chem/dend/curv_IRSp53').n
IRSp53_mvec=moose.vec('/model/chem/dend/IRSp53_m').n
cip2vec=moose.vec('/model/chem/dend/cip2').n
cip3vec=moose.vec('/model/chem/dend/cip3').n
Ipoolvec=moose.vec('/model/chem/dend/Ipool').n
curv_ir_vec=moose.vec('/model/chem/dend/curv/Enz/Enz2_cplx').n
curv=moose.vec('/model/chem/dend/curv').n
cPIP2=moose.element('/model/chem/dend/cPIP2')
##moose.vec('/model/chem/dend/sort').n=(-Ipoolvec+max(Ipoolvec))
moose.vec('/model/chem/dend/sort').n=(Ipoolvec-min(Ipoolvec))
moose.vec('/model/chem/dend/detach').n=-moose.vec('/model/chem/dend/sort').n+max(moose.vec('/model/chem/dend/sort').n)
##if max(Ipoolvec)>min(Ipoolvec):
##    plt.plot(Ipoolvec)
##    plt.plot(moose.vec('/model/chem/dend/sort').n)
##    plt.figure(2)
##    plt.plot(moose.vec('/model/chem/dend/Rad').n)
for gri in range(0,len(Cdcvec)):
   curv[gri]=1.0*((3*0.027*(curv_IRSp53vec[gri]+IRSp53_mvec[gri])**2)/(1.0+3.0*0.027*(curv_IRSp53vec[gri]+curv_ir_vec[gri]+IRSp53_mvec[gri])**2))*0.055*np.exp(-(moose.vec('/model/chem/dend/mesh')[gri].Coordinates[0]-moose.vec('/model/chem/dend/mesh')[pos].Coordinates[0])**2/(2*0.1e-6**2))
if count==1:
   maxCIR=[]
   maxIR=[]
   max_curv=[]
moose.vec('/model/chem/dend/curv').n=curv
moose.vec('/model/chem/dend/curv_pip').n=curv
if count%500==0:
  maxCIR.append(max(moose.vec('/model/chem/dend/curv_IRSp53').n))
  maxIR.append(max(moose.vec('/model/chem/dend/IRSp53_m').n))
  max_curv.append(max(moose.vec('/model/chem/dend/curv').n))
pref_curv=0.055
PIP2vec=moose.vec('/model/chem/dend/PIP2').n
plt.xlabel('Number of IRSp53 dimers')
plt.ylabel('Deformation strength')
if count%500==0:
   print 'Dimer n', moose.vec('/model/chem/dend/IRSp53_dimer').n
   print 'PIP2', moose.vec('/model/chem/dend/PIP2').n
   print 'Radius', radv
   print 'Curvature', moose.vec('/model/chem/dend/curv').n
   print 'CurvIRSp53', curv_IRSp53vec
   plt.plot(maxCIR,max_curv)
radmax=max(radv)
if count%100==0:
  print " Mass conservation check  "
  print "Sum of all forms of IRSp53 now", sum(moose.vec('/model/chem/dend/IRSp53_dimer').n)+sum(moose.vec('/model/chem/dend/IRSp53_a').n)+sum(moose.vec('/model/chem/dend/IRSp53_m').n)+sum(moose.vec('/model/chem/dend/curv_IRSp53').n)+sum(moose.vec('/model/chem/dend/cip2').n)+sum(moose.vec('/model/chem/dend/detach/Enz/Enz_cplx').n)+sum(moose.vec('/model/chem/dend/curv/Enz/Enz2_cplx').n)+sum(moose.vec('/model/chem/dend/sort/Enz/Enz_cplx').n)
  print "Initial sum", sum(moose.vec('/model/chem/dend/IRSp53_dimer').nInit)
Rn=moose.element( '/model/chem/dend/Rad' ).n
"""
    '''
    debug = moose.PyRun( '/pyrun' )
    debug.tick = 10
    debug.runString = """print "RUNNING: ", moose.element( '/model/chem/psd/z' ).n, moose.element( '/model/elec/head0' ).diameter"""
    '''
    ###moose.connect(rad,'nOut',mypyrun,'trigger')
    outputTab = moose.Table('/model/output')
    moose.connect(mypyrun, 'output', outputTab, 'input')
    moose.setClock(30, 0.01)
    moose.setClock(10, 0.01)
    moose.setClock(15, 0.01)
    moose.setClock(16, 0.01)

    mypyrun.mode = 1
    ###radCalc()
    moose.reinit()
    ###moose.start( runtime )
    test = 'False'
    step = 0

    if test == 'True':
        while step < int(runtime / 0.001):
            I_M = moose.element('/model/chem/dend/IRSp53_m').n
            I_C = moose.element('/model/chem/dend/IRSp53').n
            Rad = moose.element('/model/chem/dend/Rad').n
            height = moose.element('/model/chem/dend/height').n
            gradBAR = moose.element('/model/chem/dend/gradBAR').expr
            Radfun = moose.element('/model/chem/dend/Radfun').expr
            recBAR = moose.element('/model/chem/dend/recBAR').expr
            gradBAReval = 2.1 * 1e-28 * (I_M - I_C) * (
                1 / (0.2 * 0.2 * 1e-12)) * I_C + 0 * Rad
            print 'gradBAR', gradBAReval
            print I_C, I_M, I_P, Rad
            print moose.element('/model/chem/dend/IPreac').numKf
            if I_P > 0:
                Radfuneval = np.sqrt(
                    (55 * 4 * 1e-18) /
                    (2 * (0.02 - 0.08 * (np.log(1 / (I_P * 50 * 100 + 1))))))
                print np.log(1 / (I_P * 50 * 100 + 1))
                print(2 * (0.02 - 0.08 * (np.log(1 / (I_P * 50 * 100 + 1)))))
                print(55 * 4 * 1e-18) / (2 * (0.02 - 0.08 *
                                              (np.log(1 /
                                                      (I_P * 50 * 100 + 1)))))
                print 'Radfun', Radfuneval
            raw_input()
            moose.start(0.001)
            step = step + 1
            print step
    else:
        moose.start(0.001)
    print 'IMTab', moose.element('/graphs/IMTab').vector
    print 'IRSp53Tab', moose.element('/graphs/IRSp53Tab').vector
    print 'Radius', moose.element('/graphs/RadTab').vector
    print 'height', moose.element('/graphs/heightTab').vector
    print 'curv_IRSp53', moose.element('/graphs/curv_IRSp53Tab').vector
    print 'Ipool', moose.element('/graphs/IpoolTab').vector
    print 'sort', moose.element('/graphs/sortTab').vector
    ##print 'recruited IP', moose.vec('/model/chem/dend/IP_clx').n
    ##plt.plot(moose.vec('/model/chem/dend/IP_clx').n,label='IP at time 150')
    ##moose.start(250)
    ##if height=='True':
    ##    plt.plot(moose.vec('/model/chem/dend/height').n,label='At time 300')
    ##else:
    ##    plt.plot(moose.vec('/model/chem/dend/Rad').n,label='At time 300')
    plt.legend()
    plt.show()
Exemplo n.º 15
0
        chan.tau2 = params['tau2']
        chan.Ek = params['Erev']

# Test to check NMDA creation.
moose.le('/cell2/dend')

for key, params in synparams.items():
    if key == 'nmda':
        chan = moose.NMDAChan('/cell2/dend/' + key)
        chan.KMg_A = params['mgparams']['A']
        chan.KMg_B = params['mgparams']['B']
        chan.CMg = params['mgparams']['conc']
        chan.temperature = params['temperature']
        chan.extCa = params['extCa']
        chan.condFraction = params['condFraction']
    else:
        chan = moose.SynChan('/cell2/dend/' + key)
        chan.Gbar = params['Gbar']
        chan.tau1 = params['tau1']
        chan.tau2 = params['tau2']
        chan.Ek = params['Erev']

m = moose.connect(nmdachan, 'ICaOut', capool, 'current')

capool = moose.CaConc('/cell2/dend/capool')
moose.showfield(capool)

m = moose.connect(capool, 'concOut', nmdachan, 'setIntCa')

moose.showmsg('/cell2')
Exemplo n.º 16
0
def test_rdes1():
    rdes = rd.rdesigneur()
    rdes.buildModel()
    moose.showfield(rdes.soma)
Exemplo n.º 17
0
rdes = rd.rdesigneur(
    elecDt=50e-6,
    chemDt=0.002,
    # cellProto syntax: ['ballAndStick', 'name', somaDia, somaLength, dendDia, dendLength, numDendSegments ]
    cellProto=[['ballAndStick', 'soma', 12e-6, 12e-6, 4e-6, 100e-6, 2]],
    spineProto=[['makeActiveSpine()', 'spine']],
    spineDistrib=[['spine', '#dend#', '50e-6', '1e-6']],
)

moose.seed(123)
rdes.buildModel()
moose.reinit()

pre1 = moose.PresynMesh('pre1')
spineHeads = moose.wildcardFind("/model/elec/#head#")
print(spineHeads)
pre1.buildOnSpineHeads(spineHeads)

moose.showfield(pre1)
print("pre1 voxelVolume = ", pre1.voxelVolume)
print("pre1 voxelMidpoint = ", pre1.voxelMidpoint)

pre2 = moose.PresynMesh('pre2')
dends = moose.wildcardFind("/model/elec/#dend#")
print(dends)
pre2.buildOnDendrites(dends, 20e-6)

moose.showfield(pre2)
print("pre2 voxelVolume = ", pre2.voxelVolume)
print("pre2 voxelMidpoint = ", pre2.voxelMidpoint)
Exemplo n.º 18
0
        pass


import sys

pfile = "layer2.p"
swcfile = "538ser3sl5-cell1-2-a.CNG.swc"
container1 = "cell1"
container2 = "cell2"
cell1 = moose.loadModel(pfile, container1)
cell2 = moose.loadModel(swcfile, container2)
print("P file:")
moose.le("/cell1")
print("SWC file:")
moose.le("/cell2")
moose.showfield("/cell2/soma")
moose.showfield("/cell2/soma_1_0")
moose.showfield("/cell2/soma_2_0")

moose.showmsg("cell1/soma")
moose.showmsg("cell2/soma")

#import neuron
from neuron import h, gui

print("\n\n\n DOING NEURON NOW! \n\n\n")

soma = h.Section(name="soma")
dir(soma)
soma.insert("pas")
soma.nseg = 3
Exemplo n.º 19
0
import moose
import numpy as np
from matplotlib import pyplot as plt
from pprint import pprint  # allows for one to see nested dictionaries clearer
plt.ion()
nmdachan = moose.NMDAChan('/nmda')
moose.showfield(nmdachan)

nmdachan.KMg_A = 0.17
nmdachan.KMg_B = 0.012
nmdachan.CMg = 1.4


# Function to plot and see magnesium effect on NMDA channel
def magnesium_term(A, B, C):
    eta = 1.0 / A
    gamma = 1.0 / B
    v = np.linspace(-100e-3, 60e-3, 1000)  # voltage vector
    mg_term = 1 / (1 + eta * C * np.exp(-gamma * v))
    plt.plot(v, mg_term)


synparams = {}
mgparams = {'A': (1 / 6.0), 'B': (1 / 80.0), 'conc': 1.4}
synparams['ampa'] = {'Erev': 5e-3, 'tau1': 1.0e-3, 'tau2': 5e-3, 'Gbar': 1e-9}
synparams['nmda'] = {
    'Erev': 5e-3,
    'tau1': 1.1e-3,
    'tau2': 37.5e-3,
    'Gbar': 2e-9,
    'mgparams': mgparams,
Exemplo n.º 20
0
            neuron.gamma = 108.0
        if key == "accommodation":
            neuron.accommodating = True
            neuron.u0 = -0.065
        self.neuron = neuron
        neuron.a = params[1] * 1e3  # ms^-1 -> s^-1
        neuron.b = params[2] * 1e3  # ms^-1 -> s^-1
        neuron.c = params[3] * 1e-3  # mV -> V
        neuron.d = params[4]  # d is in mV/ms = V/s
        neuron.initVm = params[6] * 1e-3  # mV -> V
        neuron.Vmax = 0.03  # mV -> V
        if key != "accommodation":
            neuron.initU = neuron.initVm * neuron.b
        else:
            neuron.initU = -16.0  # u is in mV/ms = V/s
            moose.showfield(neuron)
        self.neurons[key] = neuron
        return neuron

    def _make_pulse_input(self, key):
        """This is for creating a pulse generator for use as a current
        source for all cases except Class_1, Class_2, resonator,
        integrator, thresh_var and accommodation."""
        try:
            return self.inputs[key]
        except KeyError:
            pass  # continue to the reset of the function
        baseLevel = 0.0
        firstWidth = 1e6
        firstDelay = 0.0
        firstLevel = IzhikevichDemo.parameters[key][5] * 1e-6
Exemplo n.º 21
0
def main():
    # Simulation information.
    simtime = 0.1
    simdt = 0.25e-5
    plotdt = 0.25e-3

    # Cell Compartment infromation
    diameter = 30e-6
    length = 50e-6
    Em = EREST_ACT + 10.613e-3
    CM = 1e-6 * 1e4
    RM = 1 / (0.3E-3 * 1e4)

    # Channel information.
    sa, x_sa = compute_comp_area(diameter, length)
    na_g = 120E-3 * sa * 1E4
    na_ek = 115E-3 + EREST_ACT
    k_g = 36e-3 * sa * 1E4
    k_ek = -12E-3 + EREST_ACT

    # Stimulus information
    inj_delay = 20E-3
    inj_amp = 1E-9
    inj_width = 40E-3

    # Create cell
    soma = create_compartment('soma',
                              length,
                              diameter,
                              RM,
                              CM,
                              initVM=EREST_ACT,
                              ELEAK=Em)

    # Create channels
    K_chan = create_channel(chan_name='K',
                            vdivs=VDIVS,
                            vmin=VMIN,
                            vmax=VMAX,
                            x_params=K_n_params,
                            xpow=4)

    Na_chan = create_channel(chan_name='Na',
                             vdivs=VDIVS,
                             vmin=VMIN,
                             vmax=VMAX,
                             x_params=Na_m_params,
                             xpow=3,
                             y_params=Na_h_params,
                             ypow=1)

    # Set conductances
    nachan = moose.copy(Na_chan, soma.path, 'Na', 1)
    kchan = moose.copy(K_chan, soma.path, 'K', 1)
    nachan = set_channel_conductance(nachan, na_g, na_ek)
    moose.showfield(nachan.path)
    kchan = set_channel_conductance(kchan, k_g, k_ek)
    moose.showfield(kchan.path)

    # Add channels to soma
    moose.connect(nachan, 'channel', soma, 'channel', 'OneToOne')
    moose.connect(kchan, 'channel', soma, 'channel', 'OneToOne')

    # connect pulse gen
    pulse_inject = create_pulse_generator(soma,
                                          inj_width,
                                          inj_amp,
                                          delay=inj_delay)

    # Output table
    soma_v_table = create_output_table(table_element='/output',
                                       table_name='somaVm')
    soma_i_table = create_output_table(table_element='/output',
                                       table_name='somaIm')

    # Connect output tables
    moose.connect(soma_v_table, 'requestOut', soma, 'getVm')
    moose.connect(soma_i_table, 'requestOut', pulse_inject, 'getOutputValue')

    # Set moose simulation clocks
    for lable in range(7):
        moose.setClock(lable, simdt)
    moose.setClock(8, plotdt)

    # Run simulation
    moose.reinit()
    moose.start(simtime)

    # Plot output tables.
    v_plot = plot_vm_table(simtime,
                           soma_v_table,
                           soma_i_table,
                           title="soma voltage")
    plt.grid(True)
    plt.legend(['v', 'i'])
    plt.show()
Exemplo n.º 22
0
soma_Vm, soma_Iex = u.createDataTables(soma, data, soma_pulse)
dend_Vm, dend_Iex = u.createDataTables(dend, data, soma_pulse)
synchan = moose.SynChan('/neuron/swagginDend/glu')
synchan.Gbar = 1e-8
synchan.tau1 = 2e-3
synchan.tau2 = 2e-3
synchan.Ek = -0.010
msg = moose.connect(dend, 'channel', synchan, 'channel')
sh = moose.SimpleSynHandler('/neuron/swagginDend/glu/synhandler')
moose.connect(sh, 'activationOut', synchan, 'activation')
sh.synapse.num = 1
sh.synapse[0].delay = 1e-3

moose.showmsg(sh)
moose.showmsg(synchan)
moose.showfield(sh.synapse[0])

# the commands above specify and connect the randSpike to a synapse on the
# dendrite
pre_syn = moose.RandSpike('presyn_input')
pre_syn.rate = 10
pre_syn.refractT = 1e-3
sh.synapse.num = 1
sh.synapse[0].delay = 5e-3
moose.connect(pre_syn, 'spikeOut', sh.synapse[0], 'addSpike')

# commands above connect another spike from a pre-synaptic neuron to the
# synapse
pre_syn2 = moose.RandSpike('pre_syn2')
pre_syn2.rate = 0
pre_syn2.refractT = 1e-3
Exemplo n.º 23
0
            neuron.gamma = 108.0
        if key == 'accommodation':
            neuron.accommodating = True
            neuron.u0 = -0.065
        self.neuron = neuron
        neuron.a = params[1] * 1e3 # ms^-1 -> s^-1
        neuron.b = params[2] * 1e3 # ms^-1 -> s^-1
        neuron.c = params[3] * 1e-3 # mV -> V
        neuron.d = params[4]  # d is in mV/ms = V/s
        neuron.initVm = params[6] * 1e-3 # mV -> V
        neuron.Vmax = 0.03 # mV -> V
        if key != 'accommodation':
            neuron.initU = neuron.initVm * neuron.b
        else:
            neuron.initU = -16.0 # u is in mV/ms = V/s
            moose.showfield(neuron)
        self.neurons[key] = neuron
        return neuron

    def _make_pulse_input(self, key):
        """This is for creating a pulse generator for use as a current
        source for all cases except Class_1, Class_2, resonator,
        integrator, thresh_var and accommodation."""
        try:
            return self.inputs[key]
        except KeyError:
            pass # continue to the reset of the function
        baseLevel = 0.0
        firstWidth = 1e6
        firstDelay = 0.0
        firstLevel = IzhikevichDemo.parameters[key][5] * 1e-6
Exemplo n.º 24
0
initVm = EREST_ACT
cond_set = {'Na': 10000, 'K': 2500}
pulse_dur = 100e-3
pulse_amp = 0.75e-9
pulse_delay1 = 20e-3
pulse_delay2 = 1e9

# Load a multi-compartment model into MOOSE and give it channels
swcfile = '33-RVT162-1-4e.CNG.swc'
container = 'gran_cell'
libraryName = '/library'
compType = 'Compartment'
gran_cell = u.createMultiCompCell(swcfile, container, libraryName, compType,
                                  chan_set, cond_set, rateParams, RM, CM, RA,
                                  initVm, Em)
moose.showfield('/gran_cell/soma')

# Re-create the python variable pointing to the gran_cell to limit results just to
# type compartment (excludes the spines and allows for createDataTables function to
# work properly)
gran_cell = moose.wildcardFind('/gran_cell/#[TYPE=Compartment]')

# Create the pulse and apply it to the granule cell's soma
g_soma_pulse = u.createPulse(gran_cell[0], 'rollingWave', pulse_dur, pulse_amp,
                             pulse_delay1, pulse_delay2)

# Create a neutral object to store the data in
gran_data = moose.Neutral('/gran_data')
gran_tables = []
for comp in gran_cell:
    gran_tables.append(u.createDataTables(comp, gran_data, g_soma_pulse))
Exemplo n.º 25
0
    soma.initVm = -65E-3
    inj_duration = 100E-3
    inj_amplitude = 0.954E-9  #0.188E-9
    pulse_1 = create_pulse_generator(soma, inj_duration, inj_amplitude)
    moose.reinit()
    moose.start(0.3)
    print(soma.Vm)


# Main call.
main()

##### Class Work -3
output = moose.Neutral('/output')
Vmtab = moose.Table('/output/somaVm')
moose.showfield(vmtab)

# To plot tables.
import pylab
t = pylab.linspace(0, 200E-3, len(vmtab.vector))
pylab.plot(t, vmtab.vector)
pylab.show()

# soma data descriptor
soma_l = 20E-6
soma_d = 20E-6

soma_RM = 2  #20000
soma_CM = 0.01  #1E-6
soma_RA = 4.0
Exemplo n.º 26
0
def main():
    """
    This example builds a simple multiscale model involving
    electrical and chemical signaling, but without spatial dimensions.
    The electrical cell model is in a single compartment and has
    voltage-gated channels, including a voltage-gated Ca channel for
    Ca influx, and a K_A channel which is regulated by the chemical
    pathways.

    The chemical model has calcium activating Calmodulin which activates
    CaM-Kinase II. The kinase phosphorylates the K_A channel to inactivate
    it.

    The net effect of the multiscale activity is a positive feedback
    loop where activity increases Ca, which activates the kinase,
    which reduces K_A, leading to increased excitability of the cell.

    In this example this results
    in a bistable neuron. In the resting state the cell does not fire,
    but if it is activated by a current pulse the cell will continue to
    fire even after the current is turned off. Application of an
    inhibitory current restores the cell to its silent state.

    Both the electrical and chemical models are loaded in from model
    description files, and these files could be replaced if one wished
    to define different models. However, there
    are model-specific Adaptor objects needed to map activity between the
    models of the two kinds. The Adaptors connect specific model entities
    between the two models. Here one Adaptor connects the electrical
    Ca_conc object to the chemical Ca pool. The other Adaptor connects
    the chemical pool representing the K_A channel to its conductance
    term in the electrical model.
    """

    runtime = 4
    elecDt = 50e-6
    chemDt = 0.005
    ePlotDt = 0.5e-3
    cPlotDt = 0.0025

    makeModel()

    moose.setClock( 8, ePlotDt )
    moose.setClock( 18, cPlotDt )
    for i in range( 0, 10 ):
        moose.setClock( i, elecDt )
    for i in range( 10, 18 ):
        moose.setClock( i, chemDt )

    graphs = moose.Neutral( '/graphs' )
    caplot = addPlot( '/model/elec/soma/Ca_conc', 'getCa', 'somaCa', 8 )
    vmplot = addPlot( '/model/elec/soma', 'getVm', 'somaVm', 8 )
    ikplot = addPlot( '/model/elec/soma/K_A', 'getIk', 'KAIk', 8 )
    addPlot( '/model/chem/kinetics/chan', 'getConc', 'chan', 18 )
    addPlot( '/model/chem/kinetics/Ca', 'getConc', 'Ca', 18 )
    addPlot( '/model/chem/kinetics/CaM', 'getConc', 'CaM', 18 )
    addPlot( '/model/chem/kinetics/Ca_CaM_CaMKII', 'getConc', 'enz', 18 )
    hsolve = moose.HSolve( '/model/elec/hsolve' )
    hsolve.dt = elecDt
    hsolve.target = '/model/elec/soma'
    moose.reinit()
    moose.showfield( '/model/elec/soma' )
    moose.element( '/model/elec/soma' ).inject = 0e-12
    moose.start( runtime )
    for i in moose.wildcardFind( '/model/elec/soma/#[ISA=ChanBase]' ):
        print( "{}  {}  {}".format( i.name, i.Gbar, i.modulation ))
    moose.element( '/model/elec/soma' ).inject = 1e-12
    moose.start( runtime )
    moose.element( '/model/elec/soma' ).inject = 0e-12
    moose.start( runtime )
    moose.element( '/model/elec/soma' ).inject = -1e-12
    moose.start( runtime )
    moose.element( '/model/elec/soma' ).inject = 0e-12
    moose.start( runtime )
    fig = plt.figure( figsize = (12,10) )
    t = numpy.arange( 0, caplot.vector.size, 1 ) * caplot.dt
    p1 = fig.add_subplot( 411 )
    p1.plot( t, caplot.vector, label="Ca elec" )
    p1.legend()
    p2 = fig.add_subplot( 412 )
    p2.plot( t, vmplot.vector, label="Vm" )
    p2.legend()
    p3 = fig.add_subplot( 413 )
    p3.plot( t, ikplot.vector, label="Ik for K_A" )
    p3.legend()
    p4 = fig.add_subplot( 414 )
    for x in moose.wildcardFind( '/graphs/#[FIELD(tick)=18]' ):
        t = numpy.arange( 0, x.vector.size, 1 ) * x.dt
        p4.plot( t, x.vector, label=x.name )
    p4.legend()
    plt.show()
    quit()
Exemplo n.º 27
0
def main():
    """
    This example builds a simple multiscale model involving
    electrical and chemical signaling, but without spatial dimensions.
    The electrical cell model is in a single compartment and has
    voltage-gated channels, including a voltage-gated Ca channel for
    Ca influx, and a K_A channel which is regulated by the chemical
    pathways.

    The chemical model has calcium activating Calmodulin which activates
    CaM-Kinase II. The kinase phosphorylates the K_A channel to inactivate
    it.

    The net effect of the multiscale activity is a positive feedback
    loop where activity increases Ca, which activates the kinase,
    which reduces K_A, leading to increased excitability of the cell.

    In this example this results
    in a bistable neuron. In the resting state the cell does not fire,
    but if it is activated by a current pulse the cell will continue to
    fire even after the current is turned off. Application of an
    inhibitory current restores the cell to its silent state.

    Both the electrical and chemical models are loaded in from model
    description files, and these files could be replaced if one wished
    to define different models. However, there
    are model-specific Adaptor objects needed to map activity between the
    models of the two kinds. The Adaptors connect specific model entities
    between the two models. Here one Adaptor connects the electrical
    Ca_conc object to the chemical Ca pool. The other Adaptor connects
    the chemical pool representing the K_A channel to its conductance
    term in the electrical model.
    """

    runtime = 4
    elecDt = 50e-6
    chemDt = 0.005
    ePlotDt = 0.5e-3
    cPlotDt = 0.0025

    makeModel()

    moose.setClock(8, ePlotDt)
    moose.setClock(18, cPlotDt)
    for i in range(0, 10):
        moose.setClock(i, elecDt)
    for i in range(10, 18):
        moose.setClock(i, chemDt)

    graphs = moose.Neutral('/graphs')
    caplot = addPlot('/model/elec/soma/Ca_conc', 'getCa', 'somaCa', 8)
    vmplot = addPlot('/model/elec/soma', 'getVm', 'somaVm', 8)
    ikplot = addPlot('/model/elec/soma/K_A', 'getIk', 'KAIk', 8)
    addPlot('/model/chem/kinetics/chan', 'getConc', 'chan', 18)
    addPlot('/model/chem/kinetics/Ca', 'getConc', 'Ca', 18)
    addPlot('/model/chem/kinetics/CaM', 'getConc', 'CaM', 18)
    addPlot('/model/chem/kinetics/Ca_CaM_CaMKII', 'getConc', 'enz', 18)
    hsolve = moose.HSolve('/model/elec/hsolve')
    hsolve.dt = elecDt
    hsolve.target = '/model/elec/soma'
    moose.reinit()
    moose.showfield('/model/elec/soma')
    moose.element('/model/elec/soma').inject = 0e-12
    moose.start(runtime)
    for i in moose.wildcardFind('/model/elec/soma/#[ISA=ChanBase]'):
        print("{}  {}  {}".format(i.name, i.Gbar, i.modulation))
    moose.element('/model/elec/soma').inject = 1e-12
    moose.start(runtime)
    moose.element('/model/elec/soma').inject = 0e-12
    moose.start(runtime)
    moose.element('/model/elec/soma').inject = -1e-12
    moose.start(runtime)
    moose.element('/model/elec/soma').inject = 0e-12
    moose.start(runtime)
    fig = plt.figure(figsize=(12, 10))
    t = numpy.arange(0, caplot.vector.size, 1) * caplot.dt
    p1 = fig.add_subplot(411)
    p1.plot(t, caplot.vector, label="Ca elec")
    p1.legend()
    p2 = fig.add_subplot(412)
    p2.plot(t, vmplot.vector, label="Vm")
    p2.legend()
    p3 = fig.add_subplot(413)
    p3.plot(t, ikplot.vector, label="Ik for K_A")
    p3.legend()
    p4 = fig.add_subplot(414)
    for x in moose.wildcardFind('/graphs/#[FIELD(tick)=18]'):
        t = numpy.arange(0, x.vector.size, 1) * x.dt
        p4.plot(t, x.vector, label=x.name)
    p4.legend()
    plt.show()
    quit()
Exemplo n.º 28
0
soma = moose.Compartment('soma')
soma = moose.element('soma')  # Returns a refence to an existant moose element.
# Doesn't create new moose element.!!!

neuron = moose.Neutral('/neuron')
soma = moose.Compartment('/neuron/soma')
dend = moose.Compartment('/neuron/dend')
data = moose.Neutral('/data')

print soma.path
print soma.name

# List elements under a moose element.
moose.le('/neuron')

# List all the attributes of a moose element.
moose.showfield('/neuron')

# Print individual attributes of moose elements to examine.
print soma.Rm, soma.Vm, soma.Cm, soma.Ra

# Allows moose to traverse into moose element to short showfield command.
moose.ce('/neuron')  # Change head node element for traversal.
moose.ce(neuron)
moose.ce()  # Change the head node to root node.

soma.Cm = 1e-9
soma.Rm = 10e6
soma.initVm = -75E-3
Exemplo n.º 29
0
rm = 2 / 10E-4
cm = 1E-6 / 10E-4
Em = -0.065

# length is 100 microns, radius is 10 microns.
Rm = rm * (2 * math.pi * 10E-6 * 100E-6)
Cm = cm / (2 * math.pi * 10E-6 * 100E-6
           )  # not understand calc using equation. :(

soma = moose.Compartment('/soma')
soma.setRm(Rm)
soma.setCm(Cm)
soma.setEm(Em)

print(soma.Rm, soma.Cm, soma.Em)
moose.showfield(soma)

#Part 2  Create a pulse gen
pulse = moose.PulseGen('pulse')
duration = 200E-3
Vm = 30E-3
I_inj = (Vm - Em) / Rm + Vm / duration
pulse.setFirstDelay(50E-3)
pulse.setFirstWidth(duration)
pulse.setFirstLevel(I_inj)
pulse.setCount(1)
moose.showfield(pulse)

# I didnot understand what is difference between tick and count :(

#Part 3 Connect pulse generator with soma.
def main():
    library = moose.Neutral('/library')
    makePassiveSoma('cell', params['dendL'], params['dendDia'])
    makeChemProto()
    rdes = rd.rdesigneur(
        turnOffElec=True,
        chemPlotDt=0.1,
        diffusionLength=params['diffusionL'],
        cellProto=[['cell', 'soma']],
        chemProto=[['hydra', 'hydra']],
        chemDistrib=[['hydra', 'soma', 'install', '1']],
        plotList=[['soma', '1', 'dend/A', 'n', '# of A'],
                  ['soma', '1', 'dend/B', 'n', '# of B']],
        #    moogList = [['soma', '1', 'dend/A', 'n', 'num of A (number)']]
    )
    moose.le('/library')
    moose.le('/library/hydra')
    moose.showfield('/library/soma/soma')
    rdes.buildModel()
    #moose.element('/model/chem/dend/B').vec[50].nInit=15.5

    A = moose.vec('/model/chem/dend/A')
    B = moose.vec('/model/chem/dend/B')
    #    A.concInit=1
    #    B.concInit=10
    moose.element('/model/chem/dend/A').vec[500].nInit = 110
    #moose.element('/model/chem/dend/A').vec[490].nInit=101
    #moose.element('/model/chem/dend/B').vec[25].nInit=0
    #A.nInit=1
    #B.nInit=15
    for i in range(0, 499):
        #moose.element('/model/chem/dend/A').vec[i].diffConst=9.45e-12
        moose.element('/model/chem/dend/A').vec[i].diffConst = 1e-14
        moose.element('/model/chem/dend/B').vec[i].diffConst = 1e-14
        #moose.element('/model/chem/dend/B').vec[i].diffConst=0.27e-09

    for i in range(500, 999):
        #moose.element('/model/chem/dend/A').vec[i].diffConst=9.45e-12
        moose.element('/model/chem/dend/A').vec[i].diffConst = 1e-14
        moose.element('/model/chem/dend/B').vec[i].diffConst = 1e-14
        #moose.element('/model/chem/dend/B').vec[i].diffConst=0.27e-09

    for i in range(0, 200):
        moose.element('/model/chem/dend/A').vec[i].diffConst = 1e-14

    for i in range(700, 999):
        moose.element('/model/chem/dend/A').vec[i].diffConst = 1e-14
    #avec = moose.vec( '/model/chem/dend/A' ).n
    #bvec = moose.vec( '/model/chem/dend/B' ).n

    print "diffconst is ", moose.element(
        '/model/chem/dend/A').vec[50].diffConst
    #plt.ion()
    #fig=plt.figure(figsize=(12,10))
    #ax=fig.add_subplot(111)
    #ax.set_ylim( 0, 5)
    #ax1=fig.add_subplot(212)
    #plt.xlabel('position')
    #plt.ylabel('# of A')
    #timeLabel = plt.text(1, 1, 'time=0.0')
    #pos=np.arange(0,A.n.size,1)
    #line1,=ax.plot(pos,A.n,label='A')
    #line2,=ax.plot(pos,B.n,label='B')
    #fig.canvas.draw()
    #displayInterval=2
    #runTime=1000
    moose.reinit()
    moose.start(2000)
    avec = moose.vec('/model/chem/dend/A').n
    bvec = moose.vec('/model/chem/dend/B').n
    plt.plot(avec)

    #moose.start(10)
    #plt.plot(avec)
    #plt.show()

    #print "Before for loop"
    #for t in range(displayInterval,runTime,displayInterval):
    #print t, "entering loop"
    #moose.start(displayInterval)
    #timeLabel.set_text( "Time = %f" % t)
    #line1.set_ydata(A.n)
    #line2.set_ydata(B.n)
    #plt.plot(avec)
    #plt.show()
    #fig.canvas.draw()

    #plt.plot(avec)

    #plt.ioff()'''

    #for i in range(98,99):
    #moose.element('/model/chem/dend/A').vec[i].diffConst=1e-06
    #moose.element('/model/chem/dend/B').vec[i].diffConst=0

    #Adot = moose.element('/model/chem/dend/A/Adot')
    #Bdot = moose.element('/model/chem/dend/B/Bdot')

    #print "\n\n\t\t Before Run", Adot, Bdot, A.nInit, B.nInit, A.n, B.n, A.concInit, B.concInit

    #moose.reinit()
    #moose.start(2000)

    #print "\n\n\t\t After Run", A.nInit, B.nInit, A.n, B.n, A.concInit, B.concInit

    # rdes.display()
    # rdes.displayMoogli( 1, 400, 0.001 )
    #avec = moose.vec( '/model/chem/dend/A' ).n
    #bvec = moose.vec( '/model/chem/dend/B' ).n
    #tab = moose.element( '/model/graphs/plot0')
    #dt = tab.dt
    #tvec=[]
    #tvec.append( tab.vector )
    # xplot = []
    # xplot.append( avec )
    ##  t = np.arange( 0, len( tvec[0] ), 1.0 ) * dt
    #plt.plot(bvec)

    #print bvec, len(bvec), bvec

    return bvec, avec