Example #1
0
def test_state_variable_access():
    G = NeuronGroup(10, 'v:volt')
    G.v = np.arange(10) * volt

    assert_equal(np.asarray(G.v[:]), np.arange(10))
    assert have_same_dimensions(G.v[:], volt)
    assert_equal(np.asarray(G.v[:]), G.v_[:])
    # Accessing single elements, slices and arrays
    assert G.v[5] == 5 * volt
    assert G.v_[5] == 5
    assert_equal(G.v[:5], np.arange(5) * volt)
    assert_equal(G.v_[:5], np.arange(5))
    assert_equal(G.v[[0, 5]], [0, 5] * volt)
    assert_equal(G.v_[[0, 5]], np.array([0, 5]))

    # Illegal indexing
    assert_raises(IndexError, lambda: G.v[0, 0])
    assert_raises(IndexError, lambda: G.v_[0, 0])
    assert_raises(TypeError, lambda: G.v[object()])
    assert_raises(TypeError, lambda: G.v_[object()])

    # A string representation should not raise any error
    assert len(str(G.v))
    assert len(repr(G.v))
    assert len(str(G.v_))
    assert len(repr(G.v_))
Example #2
0
def test_state_variables():
    '''
    Test the setting and accessing of state variables.
    '''
    G = NeuronGroup(10, 'v : volt')
    G.v = -70 * mV
    assert_raises(DimensionMismatchError, lambda: G.__setattr__('v', -70))
    G.v_ = float(-70 * mV)
    # Numpy methods should be able to deal with state variables
    # (discarding units)
    assert_allclose(np.mean(G.v), float(-70 * mV))
    # Getting the content should return a Quantity object which then natively
    # supports numpy functions that access a method
    assert_allclose(np.mean(G.v[:]), -70 * mV)

    # You should also be able to set variables with a string
    G.v = '-70*mV + i*mV'
    assert_allclose(G.v[0], -70 * mV)
    assert_allclose(G.v[9], -61 * mV)
    assert_allclose(G.v[:], -70 * mV + np.arange(10) * mV)

    # Calculating with state variables should work too
    assert all(G.v - G.v == 0)

    # And in-place modification should work as well
    G.v += 10 * mV
    G.v *= 2
    # with unit checking
    assert_raises(DimensionMismatchError, lambda: G.v.__iadd__(3 * second))
    assert_raises(DimensionMismatchError, lambda: G.v.__iadd__(3))
    assert_raises(DimensionMismatchError, lambda: G.v.__imul__(3 * second))
Example #3
0
def test_variableview_calculations():
    # Check that you can directly calculate with "variable views"
    G = NeuronGroup(10, '''x : 1
                           y : volt''')
    G.x = np.arange(10)
    G.y = np.arange(10)[::-1] * mV
    assert_allclose(G.x * G.y, np.arange(10) * np.arange(10)[::-1] * mV)
    assert_allclose(-G.x, -np.arange(10))
    assert_allclose(-G.y, -np.arange(10)[::-1] * mV)

    assert_allclose(3 * G.x, 3 * np.arange(10))
    assert_allclose(3 * G.y, 3 * np.arange(10)[::-1] * mV)
    assert_allclose(G.x * 3, 3 * np.arange(10))
    assert_allclose(G.y * 3, 3 * np.arange(10)[::-1] * mV)
    assert_allclose(G.x / 2.0, np.arange(10) / 2.0)
    assert_allclose(G.y / 2, np.arange(10)[::-1] * mV / 2)
    assert_allclose(G.x + 2, 2 + np.arange(10))
    assert_allclose(G.y + 2 * mV, 2 * mV + np.arange(10)[::-1] * mV)
    assert_allclose(2 + G.x, 2 + np.arange(10))
    assert_allclose(2 * mV + G.y, 2 * mV + np.arange(10)[::-1] * mV)
    assert_allclose(G.x - 2, np.arange(10) - 2)
    assert_allclose(G.y - 2 * mV, np.arange(10)[::-1] * mV - 2 * mV)
    assert_allclose(2 - G.x, 2 - np.arange(10))
    assert_allclose(2 * mV - G.y, 2 * mV - np.arange(10)[::-1] * mV)

    # incorrect units
    assert_raises(DimensionMismatchError, lambda: G.x + G.y)
    assert_raises(DimensionMismatchError, lambda: G.x[:] + G.y)
    assert_raises(DimensionMismatchError, lambda: G.x + G.y[:])
    assert_raises(DimensionMismatchError, lambda: G.x + 3 * mV)
    assert_raises(DimensionMismatchError, lambda: 3 * mV + G.x)
    assert_raises(DimensionMismatchError, lambda: G.y + 3)
    assert_raises(DimensionMismatchError, lambda: 3 + G.y)
Example #4
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
    assert_raises(TypeError,
                  lambda: NeuronGroup(1, '', events={'my_event': 10 * mV}))
    # 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', ''))
Example #5
0
def test_get_states():
    G = NeuronGroup(
        10, '''v : volt
                           x : 1
                           subexpr = x + v/volt : 1
                           subexpr2 = x*volt + v : volt''')
    G.v = 'i*volt'
    G.x = '10*i'
    states_units = G.get_states(['v', 'x', 'subexpr', 'subexpr2'], units=True)
    states = G.get_states(['v', 'x', 'subexpr', 'subexpr2'], units=False)

    assert len(states_units.keys()) == len(states.keys()) == 4
    assert_equal(states_units['v'], np.arange(10) * volt)
    assert_equal(states_units['x'], 10 * np.arange(10))
    assert_equal(states_units['subexpr'], 11 * np.arange(10))
    assert_equal(states_units['subexpr2'], 11 * np.arange(10) * volt)
    assert_equal(states['v'], np.arange(10))
    assert_equal(states['x'], 10 * np.arange(10))
    assert_equal(states['subexpr'], 11 * np.arange(10))
    assert_equal(states['subexpr2'], 11 * np.arange(10))

    all_states = G.get_states(units=True)
    assert set(all_states.keys()) == {'v', 'x', 'N', 't', 'dt', 'i'}
    all_states = G.get_states(units=True, subexpressions=True)
    assert set(all_states.keys()) == {
        'v', 'x', 'N', 't', 'dt', 'i', 'subexpr', 'subexpr2'
    }
Example #6
0
def test_scalar_parameter_access():
    G = NeuronGroup(
        10, '''dv/dt = freq : 1
                           freq : Hz (shared)
                           number : 1 (shared)
                           array : 1''')

    # Try setting a scalar variable
    G.freq = 100 * Hz
    assert_equal(G.freq[:], 100 * Hz)
    G.freq[:] = 200 * Hz
    assert_equal(G.freq[:], 200 * Hz)
    G.freq = 'freq - 50*Hz + number*Hz'
    assert_equal(G.freq[:], 150 * Hz)
    G.freq[:] = '50*Hz'
    assert_equal(G.freq[:], 50 * Hz)

    # Check the second method of accessing that works
    assert_equal(np.asanyarray(G.freq), 50 * Hz)

    # Check error messages
    assert_raises(IndexError, lambda: G.freq[0])
    assert_raises(IndexError, lambda: G.freq[1])
    assert_raises(IndexError, lambda: G.freq[0:1])
    assert_raises(IndexError, lambda: G.freq['i>5'])

    assert_raises(ValueError,
                  lambda: G.freq.set_item(slice(None), [0, 1] * Hz))
    assert_raises(IndexError, lambda: G.freq.set_item(0, 100 * Hz))
    assert_raises(IndexError, lambda: G.freq.set_item(1, 100 * Hz))
    assert_raises(IndexError, lambda: G.freq.set_item('i>5', 100 * Hz))
Example #7
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)
    run(5*ms)

    assert all(mon[0].I_l == mon1[0].I)
    assert all(mon[1].I_l == mon1[1].I)
Example #8
0
def test_linked_triple_linked():
    '''
    Link to a linked variable that links to a linked variable, all use indices
    '''
    G1 = NeuronGroup(2, 'a : 1')

    G2 = NeuronGroup(4, 'b : 1 (linked)')
    G2.b = linked_var(G1.a, index=np.arange(2).repeat(2))

    G3 = NeuronGroup(4, 'c: 1 (linked)')
    G3.c = linked_var(G2.b, index=np.arange(4)[::-1])

    G4 = NeuronGroup(8, 'd: 1 (linked)')
    G4.d = linked_var(G3.c, index=np.arange(4).repeat(2))

    G1.a = np.arange(2)*0.1
    assert_equal(G4.d[:], np.arange(2).repeat(2)[::-1].repeat(2)*0.1)
Example #9
0
def test_subexpression():
    G = NeuronGroup(10, '''dv/dt = freq : 1
                           freq : Hz
                           array : 1
                           expr = 2*freq + array*Hz : Hz''')
    G.freq = '10*i*Hz'
    G.array = 5
    assert_equal(G.expr[:], 2*10*np.arange(10)*Hz + 5*Hz)
Example #10
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')
    run(defaultclock.dt)
Example #11
0
def test_scalar_subexpression():
    G = NeuronGroup(10, '''dv/dt = freq : 1
                           freq : Hz (shared)
                           number : 1 (shared)
                           array : 1
                           sub = freq + number*Hz : Hz (shared)''')
    G.freq = 100*Hz
    G.number = 50
    assert G.sub[:] == 150*Hz

    assert_raises(SyntaxError, lambda: NeuronGroup(10, '''dv/dt = freq : 1
                                                          freq : Hz (shared)
                                                          array : 1
                                                          sub = freq + array*Hz : Hz (shared)'''))

    # A scalar subexpresion cannot refer to implicitly vectorized functions
    assert_raises(SyntaxError, lambda: NeuronGroup(10, 'sub = rand() : 1 (shared)'))
Example #12
0
def test_indices():
    G = NeuronGroup(10, 'v : 1')
    G.v = 'i'
    ext_var = 5
    assert_equal(G.indices[:], G.i[:])
    assert_equal(G.indices[5:], G.indices['i >= 5'])
    assert_equal(G.indices[5:], G.indices['i >= ext_var'])
    assert_equal(G.indices['v >= 5'], np.nonzero(G.v >= 5)[0])
Example #13
0
def test_ipython_html():
    G = NeuronGroup(
        10, '''dv/dt = -(v + Inp) / tau : volt
                           Inp = sin(2*pi*freq*t) : volt
                           freq : Hz''')

    # Test that HTML representation in IPython does not raise errors
    assert len(G._repr_html_())
Example #14
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)
    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)))
Example #15
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 = 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)
    run(10*ms)
    assert_equal(mon1.v[:, :], mon2.v[:, :])
    # Make sure that printing the variable values works
    assert len(str(G2.v)) > 0
    assert len(repr(G2.v)) > 0
    assert len(str(G2.v[:])) > 0
    assert len(repr(G2.v[:])) > 0
Example #16
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')
    run(defaultclock.dt)
Example #17
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))
Example #18
0
def test_unit_errors_threshold_reset():
    '''
    Test that unit errors in thresholds and resets are detected.
    '''
    for codeobj_class in codeobj_classes:
        # Unit error in threshold
        assert_raises(
            DimensionMismatchError,
            lambda: NeuronGroup(1,
                                'dv/dt = -v/(10*ms) : 1',
                                threshold='v > -20*mV',
                                codeobj_class=codeobj_class))

        # Unit error in reset
        assert_raises(
            DimensionMismatchError,
            lambda: NeuronGroup(1,
                                'dv/dt = -v/(10*ms) : 1',
                                reset='v = -65*mV',
                                codeobj_class=codeobj_class))

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

        # This should fail
        assert_raises(
            DimensionMismatchError,
            lambda: NeuronGroup(1,
                                'dv/dt = -v/(10*ms) : 1',
                                reset='''temp_var = -65*mV
                                                   v = temp_var''',
                                codeobj_class=codeobj_class))

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

        # This should fail
        assert_raises(
            DimensionMismatchError,
            lambda: NeuronGroup(1,
                                'dv/dt = -v/(10*ms) : 1',
                                reset='''v -= 60*mV''',
                                codeobj_class=codeobj_class))
Example #19
0
def test_linked_variable_incorrect():
    '''
    Test incorrect uses of linked variables.
    '''
    G1 = NeuronGroup(10, '''x : volt
                            y : 1''')
    G2 = NeuronGroup(20, '''x: volt''')
    G3 = NeuronGroup(10, '''l : volt (linked)
                            not_linked : volt''')

    # incorrect unit
    assert_raises(DimensionMismatchError, lambda: setattr(G3, 'l', linked_var(G1.y)))
    # incorrect group size
    assert_raises(ValueError, lambda: setattr(G3, 'l', linked_var(G2.x)))
    # incorrect use of linked_var
    assert_raises(ValueError, lambda: setattr(G3, 'l', linked_var(G1.x, 'x')))
    assert_raises(ValueError, lambda: setattr(G3, 'l', linked_var(G1)))
    # Not a linked variable
    assert_raises(TypeError, lambda: setattr(G3, 'not_linked', linked_var(G1.x)))
Example #20
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)
    # We don't test anything for now, except that it runs without raising an
    # error
    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
Example #21
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])
    run(defaultclock.dt)
    assert_equal(G.v[:], np.array([0, 1, 0.5]))
Example #22
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)
    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)))
Example #23
0
def test_namespace_errors():
    
    for codeobj_class in codeobj_classes:
        # model equations use unknown identifier
        G = NeuronGroup(1, 'dv/dt = -v/tau : 1', codeobj_class=codeobj_class)
        net = Network(G)
        assert_raises(KeyError, lambda: net.run(1*ms))
        
        # reset uses unknown identifier
        G = NeuronGroup(1, 'dv/dt = -v/tau : 1', reset='v = v_r',
                        codeobj_class=codeobj_class)
        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',
                        codeobj_class=codeobj_class)
        net = Network(G)
        assert_raises(KeyError, lambda: net.run(1*ms))
Example #24
0
def test_incomplete_namespace():
    '''
    Test that the namespace does not have to be complete at creation time.
    '''
    for codeobj_class in codeobj_classes:
        # This uses tau which is not defined yet (explicit namespace)
        G = NeuronGroup(1, 'dv/dt = -v/tau : 1', namespace={},
                        codeobj_class=codeobj_class)
        G.namespace['tau'] = 10*ms
        net = Network(G)
        net.run(1*ms)
        
        # This uses tau which is not defined yet (implicit namespace)
        G = NeuronGroup(1, 'dv/dt = -v/tau : 1',
                        codeobj_class=codeobj_class)
        tau = 10*ms
        net = Network(G)
        net.run(1*ms)
        del tau
Example #25
0
def test_group_variable_set_conditional_copy_to_host():

    G = NeuronGroup(1, 'v : 1')
    # uses group_variable_set_conditional template
    G.v['i < 1'] = '50'
    # connect template runs on host, requiring G.v on host after the group_variable_set
    # template call above (this tests that data is copied from device to host)
    S = Synapses(G, G)
    S.connect(condition='v_pre == 50')
    run(0 * second)
    assert len(S) == 1, len(S)
Example #26
0
def test_repr():
    G = NeuronGroup(10, '''dv/dt = -(v + Inp) / tau : volt
                           Inp = sin(2*pi*freq*t) : volt
                           freq : Hz''')

    # Test that string/LaTeX representations do not raise errors
    for func in [str, repr, sympy.latex]:
        assert len(func(G))
        assert len(func(G.equations))
        for eq in G.equations.itervalues():
            assert len(func(eq))
Example #27
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
    for codeobj_class in codeobj_classes:
        G = NeuronGroup(1, 'dv/dt = -v/tau + xi*tau**-0.5: 1',
                        codeobj_class=codeobj_class)
        net = Network(G)
        net.run(defaultclock.dt)
Example #28
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)
Example #29
0
def test_linked_variable_indexed():
    '''
    Test linking a variable with an index specified as an array
    '''
    G = NeuronGroup(10, '''x : 1
                           y : 1 (linked)''')

    G.x = np.arange(10)*0.1
    G.y = linked_var(G.x, index=np.arange(10)[::-1])
    # G.y should refer to an inverted version of G.x
    assert_equal(G.y[:], np.arange(10)[::-1]*0.1)
Example #30
0
def test_stochastic_variable_multiplicative():
    '''
    Test that a NeuronGroup with multiplicative noise can be simulated. Only
    makes sure no error occurs.
    '''
    for codeobj_class in codeobj_classes:
        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',
                        codeobj_class=codeobj_class)
        net = Network(G)
        net.run(defaultclock.dt)