示例#1
0
def test_unit_errors_threshold_reset():
    '''
    Test that unit errors in thresholds and resets are detected.
    '''
    # Unit error in threshold
    group = NeuronGroup(1, 'dv/dt = -v/(10*ms) : 1', threshold='v > -20*mV')
    assert_raises(DimensionMismatchError,
                  lambda: Network(group).run(0*ms))

    # Unit error in reset
    group = NeuronGroup(1, 'dv/dt = -v/(10*ms) : 1',
                        threshold='True',
                        reset='v = -65*mV')
    assert_raises(DimensionMismatchError,
                  lambda: Network(group).run(0*ms))

    # More complicated unit reset with an intermediate variable
    # This should pass
    group = NeuronGroup(1, 'dv/dt = -v/(10*ms) : 1',
                threshold='False',
                reset='''temp_var = -65
                         v = temp_var''')
    run(0*ms)
    # throw in an empty line (should still pass)
    group = NeuronGroup(1, 'dv/dt = -v/(10*ms) : 1',
                threshold='False',
                reset='''temp_var = -65

                         v = temp_var''')
    run(0*ms)
    # This should fail
    group = NeuronGroup(1, 'dv/dt = -v/(10*ms) : 1',
                        threshold='False',
                        reset='''temp_var = -65*mV
                                 v = temp_var''')
    assert_raises(DimensionMismatchError,
                  lambda: Network(group).run(0*ms))

    # Resets with an in-place modification
    # This should work
    group = NeuronGroup(1, 'dv/dt = -v/(10*ms) : 1',
                        threshold='False',
                        reset='''v /= 2''')
    run(0*ms)

    # This should fail
    group = NeuronGroup(1, 'dv/dt = -v/(10*ms) : 1',
                        threshold='False',
                        reset='''v -= 60*mV''')
    assert_raises(DimensionMismatchError,
              lambda: Network(group).run(0*ms))
示例#2
0
def test_incomplete_namespace():
    '''
    Test that the namespace does not have to be complete at creation time.
    '''
    # This uses tau which is not defined yet (explicit namespace)
    G = NeuronGroup(1, 'dv/dt = -v/tau : 1', namespace={})
    G.namespace['tau'] = 10*ms
    net = Network(G)
    net.run(0*ms)

    # This uses tau which is not defined yet (implicit namespace)
    G = NeuronGroup(1, 'dv/dt = -v/tau : 1')
    tau = 10*ms
    net = Network(G)
    net.run(0*ms)
示例#3
0
def test_namespace_errors():

    # model equations use unknown identifier
    G = NeuronGroup(1, 'dv/dt = -v/tau : 1')
    net = Network(G)
    assert_raises(KeyError, lambda: net.run(1*ms))

    # reset uses unknown identifier
    G = NeuronGroup(1, 'dv/dt = -v/tau : 1', threshold='False', reset='v = v_r')
    net = Network(G)
    assert_raises(KeyError, lambda: net.run(1*ms))

    # threshold uses unknown identifier
    G = NeuronGroup(1, 'dv/dt = -v/tau : 1', threshold='v > v_th')
    net = Network(G)
    assert_raises(KeyError, lambda: net.run(1*ms))
示例#4
0
def test_stochastic_variable():
    '''
    Test that a NeuronGroup with a stochastic variable can be simulated. Only
    makes sure no error occurs.
    '''
    tau = 10 * ms
    G = NeuronGroup(1, 'dv/dt = -v/tau + xi*tau**-0.5: 1')
    net = Network(G)
    net.run(defaultclock.dt)
示例#5
0
def test_syntax_errors():
    '''
    Test that syntax errors are already caught at initialization time.
    For equations this is already tested in test_equations
    '''
    
    # We do not specify the exact type of exception here: Python throws a
    # SyntaxError while C++ results in a ValueError
    # Syntax error in threshold
    group = NeuronGroup(1, 'dv/dt = 5*Hz : 1',
                        threshold='>1')
    assert_raises(Exception, lambda: Network(group).run(0*ms))

    # Syntax error in reset
    group = NeuronGroup(1, 'dv/dt = 5*Hz : 1',
                        threshold='True',
                        reset='0')
    assert_raises(Exception, lambda: Network(group).run(0*ms))
示例#6
0
def test_stochastic_variable_multiplicative():
    '''
    Test that a NeuronGroup with multiplicative noise can be simulated. Only
    makes sure no error occurs.
    '''
    mu = 0.5/second # drift
    sigma = 0.1/second #diffusion
    G = NeuronGroup(1, 'dX/dt = (mu - 0.5*second*sigma**2)*X + X*sigma*xi*second**.5: 1')
    net = Network(G)
    net.run(defaultclock.dt)
示例#7
0
def test_threshold_reset():
    '''
    Test that threshold and reset work in the expected way.
    '''
    # Membrane potential does not change by itself
    G = NeuronGroup(3, 'dv/dt = 0 / second : 1',
                    threshold='v > 1', reset='v=0.5')
    G.v = np.array([0, 1, 2])
    net = Network(G)
    net.run(defaultclock.dt)
    assert_equal(G.v[:], np.array([0, 1, 0.5]))
示例#8
0
def test_custom_events():
    G = NeuronGroup(2, '''event_time1 : second
                          event_time2 : second''',
                    events={'event1': 't>=i*ms and t<i*ms+dt',
                            'event2': 't>=(i+1)*ms and t<(i+1)*ms+dt'})
    G.run_on_event('event1', 'event_time1 = t')
    G.run_on_event('event2', 'event_time2 = t')
    net = Network(G)
    net.run(2.1*ms)
    assert_allclose(G.event_time1[:], [0, 1]*ms)
    assert_allclose(G.event_time2[:], [1, 2]*ms)
示例#9
0
def test_linked_var_in_reset_size_1():
    G1 = NeuronGroup(1, 'x:1')
    G2 = NeuronGroup(1, '''x_linked : 1 (linked)
                           y:1''',
                     threshold='y>1', reset='y=0; x_linked += 1')
    G2.x_linked = linked_var(G1, 'x')
    G2.y = 1.1
    net = Network(G1, G2)
    # In this context, x_linked should not be considered as a scalar variable
    # and therefore the reset statement should be allowed
    net.run(3*defaultclock.dt)
    assert_equal(G1.x[:], 1)
示例#10
0
def test_random_vector_values():
    # Make sure that the new "loop-invariant optimisation" does not pull out
    # the random number generation and therefore makes all neurons receiving
    # the same values
    tau = 10*ms
    G = NeuronGroup(100, 'dv/dt = -v / tau + xi*tau**-0.5: 1')
    G.v[:] = 'rand()'
    assert np.var(G.v[:]) > 0
    G.v[:] = 0
    net = Network(G)
    net.run(defaultclock.dt)
    assert np.var(G.v[:]) > 0
示例#11
0
def test_linked_var_in_reset_incorrect():
    # Raise an error if a scalar variable (linked variable from a group of size
    # 1 is set in a reset statement of a group with size > 1)
    G1 = NeuronGroup(1, 'x:1')
    G2 = NeuronGroup(2, '''x_linked : 1 (linked)
                           y:1''',
                     threshold='y>1', reset='y=0; x_linked += 1')
    G2.x_linked = linked_var(G1, 'x')
    G2.y = 1.1
    net = Network(G1, G2)
    # It is not well-defined what x_linked +=1 means in this context
    # (as for any other shared variable)
    assert_raises(SyntaxError, lambda: net.run(0*ms))
示例#12
0
def test_aliasing_in_statements():
    '''
    Test an issue around variables aliasing other variables (#259)
    '''
    runner_code = '''x_1 = x_0
                     x_0 = -1'''
    g = NeuronGroup(1, model='''x_0 : 1
                                x_1 : 1 ''', codeobj_class=NumpyCodeObject)
    custom_code_obj = g.custom_operation(runner_code)
    net = Network(g, custom_code_obj)
    net.run(defaultclock.dt)
    assert_equal(g.x_0_[:], np.array([-1]))
    assert_equal(g.x_1_[:], np.array([0]))
示例#13
0
def test_linked_variable_scalar():
    '''
    Test linked variable from a size 1 group.
    '''
    G1 = NeuronGroup(1, 'dx/dt = -x / (10*ms) : 1')
    G2 = NeuronGroup(10, '''dy/dt = (-y + x) / (20*ms) : 1
                            x : 1 (linked)''')
    G1.x = 1
    G2.y = np.linspace(0, 1, 10)
    G2.x = linked_var(G1.x)
    mon = StateMonitor(G2, 'y', record=True)
    net = Network(G1, G2, mon)
    net.run(10*ms)
示例#14
0
def test_linked_variable_correct():
    '''
    Test correct uses of linked variables.
    '''
    tau = 10*ms
    G1 = NeuronGroup(10, 'dv/dt = -v / tau : volt')
    G1.v = np.linspace(0*mV, 20*mV, 10)
    G2 = NeuronGroup(10, 'v : volt (linked)')
    G2.v = linked_var(G1.v)
    mon1 = StateMonitor(G1, 'v', record=True)
    mon2 = StateMonitor(G2, 'v', record=True)
    net = Network(G1, G2, mon1, mon2)
    net.run(10*ms)
    assert_equal(mon1.v[:, :], mon2.v[:, :])
示例#15
0
def test_incorrect_custom_event_definition():
    # Incorrect event name
    assert_raises(TypeError, lambda: NeuronGroup(1, '', events={'1event': 'True'}))
    # duplicate definition of 'spike' event
    assert_raises(ValueError, lambda: NeuronGroup(1, '', threshold='True',
                                                  events={'spike': 'False'}))
    # not a threshold
    G = NeuronGroup(1, '', events={'my_event': 10*mV})
    assert_raises(TypeError, lambda: Network(G).run(0*ms))
    # schedule for a non-existing event
    G = NeuronGroup(1, '', threshold='False', events={'my_event': 'True'})
    assert_raises(ValueError, lambda: G.set_event_schedule('another_event'))
    # code for a non-existing event
    assert_raises(ValueError, lambda: G.run_on_event('another_event', ''))
示例#16
0
def test_referred_scalar_variable():
    '''
    Test the correct handling of referred scalar variables in subexpressions
    '''
    G = NeuronGroup(10, '''out = sin(2*pi*t*freq) + x: 1
                           x : 1
                           freq : Hz (shared)''')
    G.freq = 1*Hz
    G.x = np.arange(10)
    G2 = NeuronGroup(10, '')
    G2.variables.add_reference('out', G)
    net = Network(G, G2)
    net.run(.25*second)
    assert_allclose(G2.out[:], np.arange(10)+1)
示例#17
0
def test_custom_events_schedule():
    # In the same time step: event2 will be checked and its code executed
    # before event1 is checked and its code executed
    G = NeuronGroup(2, '''x : 1
                          event_time : second''',
                    events={'event1': 'x>0',
                            'event2': 't>=(i+1)*ms and t<(i+1)*ms+dt'})
    G.set_event_schedule('event1', when='after_resets')
    G.run_on_event('event2', 'x = 1', when='resets')
    G.run_on_event('event1',
                   '''event_time = t
                      x = 0''', when='after_resets', order=1)
    net = Network(G)
    net.run(2.1*ms)
    assert_allclose(G.event_time[:], [1, 2]*ms)
示例#18
0
def test_aliasing_in_statements():
    '''
    Test an issue around variables aliasing other variables (#259)
    '''
    if prefs.codegen.target != 'numpy':
        raise SkipTest('numpy-only test')

    runner_code = '''x_1 = x_0
                     x_0 = -1'''
    g = NeuronGroup(1, model='''x_0 : 1
                                x_1 : 1 ''')
    g.run_regularly(runner_code)
    net = Network(g)
    net.run(defaultclock.dt)
    assert_equal(g.x_0_[:], np.array([-1]))
    assert_equal(g.x_1_[:], np.array([0]))
示例#19
0
def test_linked_subexpression_2():
    '''
    Test a linked variable referring to a subexpression without indices
    '''
    G = NeuronGroup(2, '''dv/dt = 100*Hz : 1
                          I = clip(v, 0, inf) : 1''',
                    threshold='v>1', reset='v=0')
    G.v = [0, .5]
    G2 = NeuronGroup(2, '''I_l : 1 (linked) ''')

    G2.I_l = linked_var(G.I)
    mon1 = StateMonitor(G, 'I', record=True)
    mon = StateMonitor(G2, 'I_l', record=True)

    net = Network(G, G2, mon, mon1)
    net.run(5*ms)

    assert all(mon[0].I_l == mon1[0].I)
    assert all(mon[1].I_l == mon1[1].I)
示例#20
0
def test_scalar_variable():
    '''
    Test the correct handling of scalar variables
    '''
    tau = 10*ms
    G = NeuronGroup(10, '''E_L : volt (shared)
                           s2 : 1 (shared)
                           dv/dt = (E_L - v) / tau : volt''')
    # Setting should work in these ways
    G.E_L = -70*mV
    assert_allclose(G.E_L[:], -70*mV)
    G.E_L[:] = -60*mV
    assert_allclose(G.E_L[:], -60*mV)
    G.E_L = 'E_L + s2*mV - 10*mV'
    assert_allclose(G.E_L[:], -70*mV)
    G.E_L[:] = '-75*mV'
    assert_allclose(G.E_L[:], -75*mV)
    net = Network(G)
    net.run(defaultclock.dt)
示例#21
0
def test_linked_subexpression():
    '''
    Test a subexpression referring to a linked variable.
    '''
    G = NeuronGroup(2, 'dv/dt = 100*Hz : 1',
                    threshold='v>1', reset='v=0')
    G.v = [0, .5]
    G2 = NeuronGroup(10, '''I = clip(x, 0, inf) : 1
                            x : 1 (linked) ''')

    G2.x = linked_var(G.v, index=np.array([0, 1]).repeat(5))
    mon = StateMonitor(G2, 'I', record=True)

    net = Network(G, G2, mon)
    net.run(5*ms)

    # Due to the linking, the first 5 and the second 5 recorded I vectors should
    # be identical
    assert all((all(mon[i].I == mon[0].I) for i in xrange(5)))
    assert all((all(mon[i+5].I == mon[5].I) for i in xrange(5)))
示例#22
0
def test_linked_variable_scalar():
    '''
    Test linked variable from a size 1 group.
    '''
    G1 = NeuronGroup(1, 'dx/dt = -x / (10*ms) : 1')
    G2 = NeuronGroup(10, '''dy/dt = (-y + x) / (20*ms) : 1
                            x : 1 (linked)''')
    G1.x = 1
    G2.y = np.linspace(0, 1, 10)
    G2.x = linked_var(G1.x)
    mon = StateMonitor(G2, 'y', record=True)
    net = Network(G1, G2, mon)
    # We don't test anything for now, except that it runs without raising an
    # error
    net.run(10*ms)
    # Make sure that printing the variable values works
    assert len(str(G2.x)) > 0
    assert len(repr(G2.x)) > 0
    assert len(str(G2.x[:])) > 0
    assert len(repr(G2.x[:])) > 0
示例#23
0
def test_linked_subexpression_3():
    '''
    Test a linked variable referring to a subexpression with indices
    '''
    G = NeuronGroup(2, '''dv/dt = 100*Hz : 1
                          I = clip(v, 0, inf) : 1''',
                    threshold='v>1', reset='v=0')
    G.v = [0, .5]
    G2 = NeuronGroup(10, '''I_l : 1 (linked) ''')

    G2.I_l = linked_var(G.I, index=np.array([0, 1]).repeat(5))
    mon1 = StateMonitor(G, 'I', record=True)
    mon = StateMonitor(G2, 'I_l', record=True)

    net = Network(G, G2, mon, mon1)
    net.run(5*ms)

    # Due to the linking, the first 5 and the second 5 recorded I vectors should
    # refer to the
    assert all((all(mon[i].I_l == mon1[0].I) for i in xrange(5)))
    assert all((all(mon[i+5].I_l == mon1[1].I) for i in xrange(5)))
示例#24
0
def runJODLInt1DLInt2(simStepSize: Quantity, simDuration: Quantity, simSettleTime: Quantity,
                      inputParsName: str, showBefore: Quantity, showAfter: Quantity,
                      DLInt1ModelProps: str, DLInt2ModelProps: str,
                      DLInt1SynapsePropsE: str, DLInt1SynapsePropsI: str,
                      DLInt2SynapseProps: str, DLInt1DLInt2SynProps: str,
                      askReplace=True):

    sns.set(style="whitegrid", rc=mplPars)

    DLInt1SynapseProps = "".join((DLInt1SynapsePropsE, DLInt1SynapsePropsI))

    opDir = os.path.join(homeFolder, DLInt1ModelProps + DLInt2ModelProps,
                         DLInt1SynapseProps + DLInt2SynapseProps + DLInt1DLInt2SynProps,
                         inputParsName)
    opFile = os.path.join(opDir, 'Traces.png')
    OPNixFile = os.path.join(opDir, 'SimResults.h5')

    if askReplace:
        if os.path.isfile(opFile):
            ch = input('Results already exist at {}. Delete?(y/n):'.format(opFile))
            if ch == 'y':
                os.remove(opFile)
                if os.path.isfile(OPNixFile):
                    os.remove(OPNixFile)
            else:
                sys.exit('User Abort!')

        elif not os.path.isdir(opDir):
            os.makedirs(opDir)
    else:
        if os.path.isfile(opFile):
            os.remove(opFile)
            if os.path.isfile(OPNixFile):
                os.remove(OPNixFile)

        elif not os.path.isdir(opDir):
            os.makedirs(opDir)

    inputPars = getattr(inputParsList, inputParsName)


    net = Network()
    JO = JOSpikes265(nOutputs=1, simSettleTime=simSettleTime, **inputPars)
    net.add(JO.JOSGG)

    DLInt1PropsDict = getattr(AdExpPars, DLInt1ModelProps)
    dlint1 = VSNeuron(**AdExp, inits=DLInt1PropsDict, name='dlint1')
    dlint1.recordSpikes()
    dlint1.recordMembraneV()

    if DLInt1SynapsePropsE:
        dlint1.addSynapse(synName="ExiJO", sourceNG=JO.JOSGG, **exp2Syn,
                              synParsInits=getattr(synapsePropsList, DLInt1SynapsePropsE),
                              synStateInits=exp2SynStateInits,
                              sourceInd=0, destInd=0
                              )
    if DLInt1SynapsePropsI:
        dlint1.addSynapse(synName="InhJO", sourceNG=JO.JOSGG, **exp2Syn,
                              synParsInits=getattr(synapsePropsList, DLInt1SynapsePropsI),
                              synStateInits=exp2SynStateInits,
                              sourceInd=0, destInd=0
                              )

    dlint1.addToNetwork(net)

    DLInt2PropsDict = getattr(AdExpPars, DLInt2ModelProps)
    dlint2 = VSNeuron(**AdExp, inits=DLInt2PropsDict, name='dlint2')
    dlint2.recordMembraneV()
    dlint2.recordSpikes()

    if DLInt2SynapseProps:
        dlint2.addSynapse(synName="JOExi", sourceNG=JO.JOSGG, **exp2Syn,
                              synParsInits=getattr(synapsePropsList, DLInt2SynapseProps),
                              synStateInits=exp2SynStateInits,
                              sourceInd=0, destInd=0
                              )

    if DLInt1DLInt2SynProps:
        dlint2.addSynapse(synName="DLInt1", sourceNG=dlint1.ng, **exp2Syn,
                              synParsInits=getattr(synapsePropsList, DLInt1DLInt2SynProps),
                              synStateInits=exp2SynStateInits,
                              sourceInd=0, destInd=0
                              )


    dlint2.addToNetwork(net)
    defaultclock.dt = simStepSize
    totalSimDur = simDuration + simSettleTime
    net.run(totalSimDur, report='text')

    simT, DLInt1_memV = dlint1.getMemVTrace()
    DLInt1_spikeTimes = dlint1.getSpikes()
    fig, axs = plt.subplots(nrows=3, figsize=(10, 6.25), sharex='col')
    axs[0].plot(simT / units.ms, DLInt1_memV / units.mV)
    spikesY = DLInt1_memV.min() + 1.05 * (DLInt1_memV.max() - DLInt1_memV.min())
    axs[0].plot(DLInt1_spikeTimes / units.ms, [spikesY / units.mV] * DLInt1_spikeTimes.shape[0], 'k^')
    axs[0].set_ylabel('DLInt1 \nmemV (mV)')
    axs[0].set_xlim([(simSettleTime - showBefore) / units.ms,
                     (totalSimDur + showAfter) / units.ms])

    simT, DLInt2_memV = dlint2.getMemVTrace()
    DLInt2_spikeTimes = dlint2.getSpikes()
    axs[1].plot(simT / units.ms, DLInt2_memV / units.mV)
    spikesY = DLInt2_memV.min() + 1.05 * (DLInt2_memV.max() - DLInt2_memV.min())
    axs[1].plot(DLInt2_spikeTimes / units.ms, [spikesY / units.mV] * DLInt2_spikeTimes.shape[0], 'k^')
    axs[1].set_ylabel('DLInt2 \nmemV (mV)')

    sineInput = getSineInput(simDur=simDuration, simStepSize=simStepSize,
                             sinPulseDurs=inputPars['sinPulseDurs'],
                             sinPulseStarts=inputPars['sinPulseStarts'],
                             freq=265 * units.Hz, simSettleTime=simSettleTime)
    axs[2].plot(simT / units.ms, sineInput, 'r-', label='Vibration Input')
    axs[2].plot(JO.spikeTimes / units.ms, [sineInput.max() * 1.05] * len(JO.spikeTimes), 'k^',
            label='JO Spikes')
    axs[2].legend(loc='upper right')
    axs[2].set_xlabel('time (ms)')
    axs[2].set_ylabel('Vibration \nInput/JO\n Spikes')
    fig.tight_layout()
    fig.canvas.draw()
    fig.savefig(opFile, dpi=150)
    plt.close(fig.number)
    del fig

    dlint1MemVAS = AnalogSignal(signal=DLInt1_memV /units.mV,
                                sampling_period=(simStepSize / units.ms) * qu.ms,
                                t_start=0 * qu.mV,
                                units="mV",
                                name="DLInt1 MemV")
    dlint2MemVAS = AnalogSignal(signal=DLInt2_memV / units.mV,
                                sampling_period=(simStepSize / units.ms) * qu.ms,
                                t_start=0 * qu.mV,
                                units="mV",
                                name="DLInt2 MemV")
    inputAS = AnalogSignal(signal=sineInput,
                                sampling_period=(simStepSize / units.ms) * qu.ms,
                                t_start=0 * qu.mV,
                                units="um",
                                name="Input Vibration Signal")
    dlint1SpikesQU = (DLInt1_spikeTimes / units.ms) * qu.ms
    dlint2SpikesQU = (DLInt2_spikeTimes / units.ms) * qu.ms
    joSpikesQU = (JO.spikeTimes / units.ms) * qu.ms

    nixFile = nixio.File.open(OPNixFile, mode=nixio.FileMode.ReadWrite)

    neuronModels = nixFile.create_section("Neuron Models", "Model Parameters")


    DLInt1PropsSec = neuronModels.create_section("DL-Int-1", "AdExp")

    for propName, propVal in DLInt1PropsDict.items():
        addBrianQuantity2Section(DLInt1PropsSec, propName, propVal)

    DLInt2PropsSec = neuronModels.create_section("DL-Int-2", "AdExp")

    for propName, propVal in DLInt2PropsDict.items():
        addBrianQuantity2Section(DLInt2PropsSec, propName, propVal)

    inputSec = nixFile.create_section("Input Parameters", "Sinusoidal Pulses")

    for parName, parVal in inputPars.items():
        addBrianQuantity2Section(inputSec, parName, parVal)

    addBrianQuantity2Section(inputSec, "simSettleTime", simSettleTime)

    brianSimSettingsSec = nixFile.create_section("Simulation Parameters", "Brian Simulation")
    addBrianQuantity2Section(brianSimSettingsSec, "simStepSize", simStepSize)
    addBrianQuantity2Section(brianSimSettingsSec, "totalSimDuration", totalSimDur)
    brianSimSettingsSec.create_property("method", nixio.Value("euler"))


    synPropsSec = nixFile.create_section("Synapse Models", "Model Parameters")

    if DLInt1SynapsePropsE:

        JODLInt1SynESec = synPropsSec.create_section("JODLInt1Exi", "DoubleExpSyn")
        JODLInt1SynEDict = getattr(synapsePropsList, DLInt1SynapsePropsE)

        for propName, propVal in JODLInt1SynEDict.items():
            addBrianQuantity2Section(JODLInt1SynESec, propName, propVal)

        JODLInt1SynESec.create_property("PreSynaptic Neuron", nixio.Value("JO"))
        JODLInt1SynESec.create_property("PostSynaptic Neuron", nixio.Value("DLInt1"))


    if DLInt1SynapsePropsI:

        JODLInt1SynISec = synPropsSec.create_section("JODLInt1Inh", "DoubleExpSyn")
        JODLInt1SynIDict = getattr(synapsePropsList, DLInt1SynapsePropsI)

        for propName, propVal in JODLInt1SynIDict.items():
            addBrianQuantity2Section(JODLInt1SynISec, propName, propVal)
        JODLInt1SynISec.create_property("PreSynaptic Neuron", nixio.Value("JO"))
        JODLInt1SynISec.create_property("PostSynaptic Neuron", nixio.Value("DLInt1"))

    if DLInt2SynapseProps:

        JODLInt2SynESec = synPropsSec.create_section("JODLInt2Exi", "DoubleExpSyn")
        JODLInt2SynEDict = getattr(synapsePropsList, DLInt2SynapseProps)

        for propName, propVal in JODLInt2SynEDict.items():
            addBrianQuantity2Section(JODLInt2SynESec, propName, propVal)
        JODLInt2SynESec.create_property("PreSynaptic Neuron", nixio.Value("JO"))
        JODLInt2SynESec.create_property("PostSynaptic Neuron", nixio.Value("DLInt2"))

    if DLInt1DLInt2SynProps:

        DLInt1DLInt2SynSec = synPropsSec.create_section("DLInt1DLInt2Inh", "DoubleExpSyn")
        DLInt1DLInt2SynDict = getattr(synapsePropsList, DLInt1DLInt2SynProps)

        for propName, propVal in DLInt1DLInt2SynDict.items():
            addBrianQuantity2Section(DLInt1DLInt2SynSec, propName, propVal)
        DLInt1DLInt2SynSec.create_property("PreSynaptic Neuron", nixio.Value("DLInt1"))
        DLInt1DLInt2SynSec.create_property("PostSynaptic Neuron", nixio.Value("DLInt2"))


    blk = nixFile.create_block("Simulation Traces", "Brian Output")
    DLInt1DA = addAnalogSignal2Block(blk, dlint1MemVAS)
    DLInt2DA = addAnalogSignal2Block(blk, dlint2MemVAS)
    inputDA = addAnalogSignal2Block(blk, inputAS)
    addMultiTag("DLInt1 Spikes", type="Spikes", positions=dlint1SpikesQU,
                blk=blk, refs=[DLInt1DA])
    addMultiTag("DLInt2 Spikes", type="Spikes", positions=dlint2SpikesQU,
                blk=blk, refs=[DLInt2DA])
    addMultiTag("JO Spikes", type="Spikes", positions=joSpikesQU,
                blk=blk, refs=[inputDA])


    nixFile.close()
                     inputParsName)
if os.path.isdir(opDir):
    ch = input('Results already exist at {}. Delete?(y/n):'.format(opDir))
    if ch == 'y':
        shutil.rmtree(opDir)
os.makedirs(opDir)

period265 = (1 / 265)
inputPars = getattr(inputParsList, inputParsName)
JO = JOSpikes265(nOutputs=1, simSettleTime=simSettleTime, **inputPars)
dlint2.addExp2Synapses(name='JO',
                       nSyn=1,
                       sourceNG=JO.JOSGG,
                       sourceInd=0,
                       **getattr(synapsePropsList, NeuronSynapseProps))
net = Network()
net.add(JO.JOSGG)
dlint2.addToNetwork(net)
defaultclock.dt = simStepSize
totalSimDur = simDuration + simSettleTime
net.run(totalSimDur, report='text')

simT, memV = dlint2.getMemVTrace()
spikeTimes = dlint2.getSpikes()
fig, axs = plt.subplots(nrows=2, figsize=(10, 6.25), sharex='col')
axs[0].plot(simT / units.ms, memV / units.mV)
spikesY = memV.min() + 1.05 * (memV.max() - memV.min())
axs[0].plot(spikeTimes / units.ms, [spikesY / units.mV] * spikeTimes.shape[0],
            'k^')
axs[0].set_ylabel('DLInt1 \nmemV (mV)')
axs[0].set_xlim([simSettleTime / units.ms - 50, totalSimDur / units.ms + 50])
示例#26
0
def test_namespace_warnings():
    G = NeuronGroup(1, '''x : 1
                          y : 1''',
                    # unique names to get warnings every time:
                    name='neurongroup_'+str(uuid.uuid4()).replace('-', '_'))
    # conflicting variable in namespace
    y = 5
    with catch_logs() as l:
        G.x = 'y'
        assert len(l) == 1, 'got %s as warnings' % str(l)
        assert l[0][1].endswith('.resolution_conflict')

    del y

    # conflicting variables with special meaning
    i = 5
    N = 3
    with catch_logs() as l:
        G.x = 'i / N'
        assert len(l) == 2, 'got %s as warnings' % str(l)
        assert l[0][1].endswith('.resolution_conflict')
        assert l[1][1].endswith('.resolution_conflict')

    del i
    del N
    # conflicting variables in equations
    y = 5*Hz
    G = NeuronGroup(1, '''y : Hz
                          dx/dt = y : 1''',
                    # unique names to get warnings every time:
                    name='neurongroup_'+str(uuid.uuid4()).replace('-', '_'))

    net = Network(G)
    with catch_logs() as l:
        net.run(0*ms)
        assert len(l) == 1, 'got %s as warnings' % str(l)
        assert l[0][1].endswith('.resolution_conflict')
    del y

    i = 5
    # i is referring to the neuron number:
    G = NeuronGroup(1, '''dx/dt = i*Hz : 1''',
                    # unique names to get warnings every time:
                    name='neurongroup_'+str(uuid.uuid4()).replace('-', '_'))
    net = Network(G)
    with catch_logs() as l:
        net.run(0*ms)
        assert len(l) == 1, 'got %s as warnings' % str(l)
        assert l[0][1].endswith('.resolution_conflict')
    del i

    # Variables that are used internally but not in equations should not raise
    # a warning
    N = 3
    i = 5
    dt = 1*ms
    G = NeuronGroup(1, '''dx/dt = x/(10*ms) : 1''',
                    # unique names to get warnings every time:
                    name='neurongroup_'+str(uuid.uuid4()).replace('-', '_'))
    net = Network(G)
    with catch_logs() as l:
        net.run(0*ms)
        assert len(l) == 0, 'got %s as warnings' % str(l)
示例#27
0
    def create_lems_model(self, network=None, namespace={}, initializers={},
                                           constants_file=None, includes=[],
                                           recordingsname='recording'):
        """
        From given *network* returns LEMS model object.

        Parameters
        ----------
        network : str, optional
            all brian objects collected into netowrk or None. In the
            second case brian2 objects are collected autmatically from
            the above scope.
        namespace : dict
            namespace variables defining extra model parameters
        initializers : dict
            all values which need to be initialized before simulation
            running
        constants_file : str, optional
            file with units as constants definitions, if None an
            LEMS_CONSTANTS_XML is added automatically
        includes : list of str
            all additional XML files added in preamble
        recordingsname : str, optional
            output of LEMS simulation recordings, values with extension
            .dat and spikes with .spikes, default 'recording'
        """
        if network is None:
            net = Network(collect(level=1))
        else:
            net = network

        if not constants_file:
            self._model.add(lems.Include(LEMS_CONSTANTS_XML))
        else:
            self._model.add(lems.Include(constants_file))
        includes = set(includes)
        for incl in INCLUDES:
            includes.add(incl)
        neuron_groups  = [o for o in net.objects if type(o) is NeuronGroup]
        state_monitors = [o for o in net.objects if type(o) is StateMonitor]
        spike_monitors = [o for o in net.objects if type(o) is SpikeMonitor]
        
        for o in net.objects:
            if type(o) not in [NeuronGroup, StateMonitor, SpikeMonitor,
                               Thresholder, Resetter, StateUpdater]:
                logger.warn("""{} export functionality
                               is not implemented yet.""".format(type(o).__name__))
        # --- not fully implemented
        synapses       = [o for o in net.objects if type(o) is Synapses]
        netinputs      = [o for o in net.objects if type(o) is PoissonInput]
        # ---
        #if len(synapses) > 0:
        #    logger.warn("Synpases export functionality is not implemented yet.")
        #if len(netinputs) > 0:
        #    logger.warn("Network Input export functionality is not implemented yet.")
        if len(netinputs) > 0:
            includes.add(LEMS_INPUTS)
        for incl in includes:
            self.add_include(incl)
        # First step is to add individual neuron deifinitions and initialize
        # them by MultiInstantiate
        for e, obj in enumerate(neuron_groups):
            self.add_neurongroup(obj, e, namespace, initializers)
        # DOM structure of the whole model is constructed below
        self._dommodel = self._model.export_to_dom()
        # input support - currently only Poisson Inputs
        for e, obj in enumerate(netinputs):
            self.add_input(obj, counter=e)
        # A population should be created in *make_multiinstantiate*
        # so we can add it to our DOM structure.
        if self._population:
            self._extend_dommodel(self._population)
        # if some State or Spike Monitors occur we support them by
        # Simulation tag
        self._model_namespace['simulname'] = "sim1"
        self._simulation = NeuroMLSimulation(self._model_namespace['simulname'],
                                             self._model_namespace['networkname'])

        for e, obj in enumerate(state_monitors):
            self.add_statemonitor(obj, filename=recordingsname, outputfile=True)
        for e, obj in enumerate(spike_monitors):
            self.add_spikemonitor(obj, filename=recordingsname)
        simulation = self._simulation.build()
        self._extend_dommodel(simulation)
        target = NeuroMLTarget(self._model_namespace['simulname'])
        target = target.build()
        self._extend_dommodel(target)