示例#1
0
def test_network_copy():
    x = Counter()
    net = Network(x)
    net2 = Network()
    for obj in net.objects:
        net2.add(obj)
    net2.run(1 * ms)
    assert_equal(x.count, 10)
    net.run(1 * ms)
    assert_equal(x.count, 20)
示例#2
0
def test_multiple_runs_defaultclock():
    defaultclock.dt = 0.1*ms
    G = NeuronGroup(1, 'dv/dt = -v / (10*ms) : 1')
    net = Network(G)
    net.run(0.5*ms)

    # The new dt is not compatible with the previous time but it should not
    # raise an error because we start a new simulation at time 0
    defaultclock.dt = 1*ms
    G = NeuronGroup(1, 'dv/dt = -v / (10*ms) : 1')
    net = Network(G)
    net.run(1*ms)
示例#3
0
def test_network_stop():
    # test that Network.stop and global stop() work correctly
    net = Network()
    x = Stopper(10, net.stop)
    net.add(x)
    net.run(10*ms)
    assert_equal(defaultclock.t, 1*ms)
    
    x = Stopper(10, stop)
    net = Network(x)
    net.run(10*ms)
    assert_equal(defaultclock.t, 1*ms)
示例#4
0
def test_incorrect_network_use():
    '''Test some wrong uses of `Network` and `MagicNetwork`'''
    assert_raises(TypeError, lambda: Network(name='mynet',
                                             anotherkwd='does not exist'))
    assert_raises(TypeError, lambda: Network('not a BrianObject'))
    net = Network()
    assert_raises(TypeError, lambda: net.add('not a BrianObject'))
    assert_raises(ValueError, lambda: MagicNetwork())
    G = NeuronGroup(10, 'v:1')
    net.add(G)
    assert_raises(TypeError, lambda: net.remove(object()))
    assert_raises(MagicError, lambda: magic_network.add(G))
    assert_raises(MagicError, lambda: magic_network.remove(G))
示例#5
0
def test_multiple_networks_invalid():
    x = Counter()
    net = Network(x)
    net.run(1*ms)
    try:
        run(1*ms)
        raise AssertionError('Expected a RuntimeError')
    except RuntimeError:
        pass  # this is expected

    try:
        net2 = Network(x)
        raise AssertionError('Expected a RuntimeError')
    except RuntimeError:
        pass  # this is expected
示例#6
0
def run_network(traj):
    """Runs brian network consisting of
        200 inhibitory IF neurons"""

    eqs = '''
    dv/dt=(v0-v)/(5*ms) : volt (unless refractory)
    v0 : volt
    '''
    group = NeuronGroup(100,
                        model=eqs,
                        threshold='v>10 * mV',
                        reset='v = 0*mV',
                        refractory=5 * ms)
    group.v0 = traj.par.v0
    group.v = np.random.rand(100) * 10.0 * mV

    syn = Synapses(group, group, on_pre='v-=1*mV')
    syn.connect('i != j', p=0.2)

    spike_monitor = SpikeMonitor(group, variables=['v'])
    voltage_monitor = StateMonitor(group, 'v', record=True)
    pop_monitor = PopulationRateMonitor(group, name='pop' + str(traj.v_idx))

    net = Network(group, syn, spike_monitor, voltage_monitor, pop_monitor)
    net.run(0.25 * second, report='text')

    traj.f_add_result(Brian2MonitorResult, 'spikes', spike_monitor)
    traj.f_add_result(Brian2MonitorResult, 'v', voltage_monitor)
    traj.f_add_result(Brian2MonitorResult, 'pop', pop_monitor)
示例#7
0
def test_ExportDevice_options():
    """
    Test the run and build options of ExportDevice
    """
    # test1
    set_device('exporter')
    grp = NeuronGroup(10, 'eqn = 1:1', method='exact')
    run(100 * ms)
    _ = StateMonitor(grp, 'eqn', record=False)
    with pytest.raises(RuntimeError):
        run(100 * ms)

    # test2
    device.reinit()
    with pytest.raises(RuntimeError):
        device.build()

    # test3
    start_scope()
    net = Network()
    set_device('exporter', build_on_run=False)
    grp = NeuronGroup(10, 'eqn = 1:1', method='exact')
    net.add(grp)
    net.run(10 * ms)
    pogrp = PoissonGroup(10, rates=10 * Hz)
    net.add(pogrp)
    net.run(10 * ms)
    mon = StateMonitor(grp, 'eqn', record=False)
    net.add(mon)
    net.run(10 * ms)
    device.build()
    device.reinit()
示例#8
0
    def create_net():
        # Use a bit of a complicated spike and connection pattern with
        # heterogeneous delays

        # Note: it is important that all objects have the same name, this would
        # be the case if we were running this in a new process but to not rely
        # on garbage collection we will assign explicit names here
        source = SpikeGeneratorGroup(
            5,
            np.arange(5).repeat(3),
            [3, 4, 1, 2, 3, 7, 5, 4, 1, 0, 5, 9, 7, 8, 9] * ms,
            name='source')
        target = NeuronGroup(10, 'v:1', name='target')
        synapses = Synapses(source,
                            target,
                            model='w:1',
                            on_pre='v+=w',
                            name='synapses')
        synapses.connect('j>=i')
        synapses.w = 'i*1.0 + j*2.0'
        synapses.delay = '(5-i)*ms'
        state_mon = StateMonitor(target, 'v', record=True, name='statemonitor')
        input_spikes = SpikeMonitor(source, name='input_spikes')
        net = Network(source, target, synapses, state_mon, input_spikes)
        return net
示例#9
0
    def __init__(self, group=None):
        if group is None:
            # default to Izhikevich model neuron
            eq = '''dv/dt = (0.04*active/ms/mV + 0.04/ms/mV)*v**2+(5/ms)*v+140*mV/ms-w + I : volt (unless refractory)
                    dw/dt = (0.02/ms)*((0.2/ms)*v-w) : volt/second
                    active : 1
                    I : volt/second'''
            # create 1 neuron with 1 output
            self.group = Neuron(
                NeuronGroup(1,
                            eq,
                            threshold='v > 50*mV',
                            reset='v = -50*mV',
                            refractory=10 * ms,
                            method='rk2'))
        else:
            self.group = group

        self.state_monitor = StateMonitor(self.group, 'v',
                                          record=True)  # monitor voltages
        self.spike_monitor = SpikeMonitor(self.group)
        self.operator = NetworkOperation(self.update_active, dt=100 * ms)

        # initialise network object for neuron to run in and add elements
        self.network = Network()
        self.network.add(self.group)
        self.network.add(self.state_monitor)
        self.network.add(self.spike_monitor)
        self.network.add(self.operator)

        self.input = 0
示例#10
0
def test_incorrect_dt_defaultclock():
    defaultclock.dt = 0.5*ms
    G = NeuronGroup(1, 'dv/dt = -v / (10*ms) : 1')
    net = Network(G)
    net.run(0.5*ms)
    defaultclock.dt = 1*ms
    assert_raises(ValueError, lambda: net.run(0*ms))
示例#11
0
def test_network_operations():
    # test NetworkOperation and network_operation
    seq = []
    def f1():
        seq.append('a')
    op1 = NetworkOperation(f1, when='start', order=1)
    @network_operation
    def f2():
        seq.append('b')
    @network_operation(when='end', order=1)
    def f3():
        seq.append('c')

    # In complex frameworks, network operations might be object methods that
    # access some common data
    class Container(object):
        def __init__(self):
            self.g1_data = 'B'
            self.g2_data = 'C'

        def g1(self):
            seq.append(self.g1_data)

        def g2(self):
            seq.append(self.g2_data)

    c = Container()
    c_op1 = NetworkOperation(c.g1)
    c_op2 = NetworkOperation(c.g2, when='end', order=1)
    net = Network(op1, f2, f3, c_op1, c_op2)
    net.run(1*ms)

    assert_equal(''.join(seq), 'bBacC'*10)
示例#12
0
def test_dependency_check():
    def create_net():
        G = NeuronGroup(10, 'v: 1', threshold='False')
        dependent_objects = [
                             StateMonitor(G, 'v', record=True),
                             SpikeMonitor(G),
                             PopulationRateMonitor(G),
                             Synapses(G, G, pre='v+=1', connect=True)
                             ]
        return dependent_objects

    dependent_objects = create_net()
    # Trying to simulate the monitors/synapses without the group should fail
    for obj in dependent_objects:
        assert_raises(ValueError, lambda: Network(obj).run(0*ms))

    # simulation with a magic network should work when we have an explicit
    # reference to one of the objects, but the object should be inactive and
    # we should get a warning
    assert all(obj.active for obj in dependent_objects)
    for obj in dependent_objects:  # obj is our explicit reference
        with catch_logs() as l:
            run(0*ms)
            dependency_warnings = [msg[2] for msg in l
                                   if msg[1] == 'brian2.core.magic.dependency_warning']
            assert len(dependency_warnings) == 1
        assert not obj.active
示例#13
0
def test_store_restore():
    source = NeuronGroup(10, '''dv/dt = rates : 1
                                rates : Hz''', threshold='v>1', reset='v=0')
    source.rates = 'i*100*Hz'
    target = NeuronGroup(10, 'v:1')
    synapses = Synapses(source, target, model='w:1', pre='v+=w', connect='i==j')
    synapses.w = 'i*1.0'
    synapses.delay = 'i*ms'
    state_mon = StateMonitor(target, 'v', record=True)
    spike_mon = SpikeMonitor(source)
    net = Network(source, target, synapses, state_mon, spike_mon)
    net.store()  # default time slot
    net.run(10*ms)
    net.store('second')
    net.run(10*ms)
    v_values = state_mon.v[:, :]
    spike_indices, spike_times = spike_mon.it_

    net.restore() # Go back to beginning
    assert defaultclock.t == 0*ms
    assert net.t == 0*ms
    net.run(20*ms)
    assert_equal(v_values, state_mon.v[:, :])
    assert_equal(spike_indices, spike_mon.i[:])
    assert_equal(spike_times, spike_mon.t_[:])

    # Go back to middle
    net.restore('second')
    assert defaultclock.t == 10*ms
    assert net.t == 10*ms
    net.run(10*ms)
    assert_equal(v_values, state_mon.v[:, :])
    assert_equal(spike_indices, spike_mon.i[:])
    assert_equal(spike_times, spike_mon.t_[:])
示例#14
0
def test_incorrect_dt_custom_clock():
    clock = Clock(dt=0.5*ms)
    G = NeuronGroup(1, 'dv/dt = -v / (10*ms) : 1', clock=clock)
    net = Network(G)
    net.run(0.5*ms)
    clock.dt = 1*ms
    assert_raises(ValueError, lambda: net.run(0*ms))
示例#15
0
def test_progress_report_incorrect():
    '''
    Test wrong use of the report option
    '''
    G = NeuronGroup(1, '')
    net = Network(G)
    assert_raises(ValueError, lambda: net.run(1*ms, report='unknown'))
    assert_raises(TypeError, lambda: net.run(1*ms, report=object()))
示例#16
0
def test_network_different_clocks():
    NameLister.updates[:] = []
    # Check that a network with two different clocks functions correctly
    x = NameLister(name='x', dt=1*ms, order=0)
    y = NameLister(name='y', dt=3*ms, order=1)
    net = Network(x, y)
    net.run(10*ms)
    assert_equal(''.join(NameLister.updates), 'xyxxxyxxxyxxxy')
示例#17
0
def test_network_contains():
    '''
    Test `Network.__contains__`.
    '''
    G = NeuronGroup(1, 'v:1', name='mygroup')
    net = Network(G)
    assert 'mygroup' in net
    assert 'neurongroup' not in net
示例#18
0
def test_profile_ipython_html():
    G = NeuronGroup(10, 'dv/dt = -v / (10*ms) : 1', threshold='v>1',
                    reset='v=0', name='profile_test')
    G.v = 1.1
    net = Network(G)
    net.run(1*ms, profile=True)
    summary = profiling_summary(net)
    assert len(summary._repr_html_())
示例#19
0
def test_network_different_when():
    # Check that a network with different when attributes functions correctly
    NameLister.updates[:] = []
    x = NameLister(name='x', when='start')
    y = NameLister(name='y', when='end')
    net = Network(x, y)
    net.run(0.3*ms)
    assert_equal(''.join(NameLister.updates), 'xyxyxy')
示例#20
0
def test_network_t():
    # test that Network.t works as expected
    c1 = Clock(dt=1 * ms)
    c2 = Clock(dt=2 * ms)
    x = Counter(when=c1)
    y = Counter(when=c2)
    net = Network(x, y)
    net.run(4 * ms)
    assert_equal(c1.t, 4 * ms)
    assert_equal(c2.t, 4 * ms)
    assert_equal(net.t, 4 * ms)
    net.run(1 * ms)
    assert_equal(c1.t, 5 * ms)
    assert_equal(c2.t, 6 * ms)
    assert_equal(net.t, 5 * ms)
    assert_equal(x.count, 5)
    assert_equal(y.count, 3)
    net.run(0.5 * ms)  # should only update x
    assert_equal(c1.t, 6 * ms)
    assert_equal(c2.t, 6 * ms)
    assert_equal(net.t, 5.5 * ms)
    assert_equal(x.count, 6)
    assert_equal(y.count, 3)
    net.run(0.5 * ms)  # shouldn't do anything
    assert_equal(c1.t, 6 * ms)
    assert_equal(c2.t, 6 * ms)
    assert_equal(net.t, 6 * ms)
    assert_equal(x.count, 6)
    assert_equal(y.count, 3)
    net.run(0.5 * ms)  # should update x and y
    assert_equal(c1.t, 7 * ms)
    assert_equal(c2.t, 8 * ms)
    assert_equal(net.t, 6.5 * ms)
    assert_equal(x.count, 7)
    assert_equal(y.count, 4)

    del c1, c2, x, y, net

    # now test with magic run
    c1 = Clock(dt=1 * ms)
    c2 = Clock(dt=2 * ms)
    x = Counter(when=c1)
    y = Counter(when=c2)
    run(4 * ms)
    assert_equal(c1.t, 4 * ms)
    assert_equal(c2.t, 4 * ms)
    assert_equal(x.count, 4)
    assert_equal(y.count, 2)
    run(4 * ms)
    assert_equal(c1.t, 8 * ms)
    assert_equal(c2.t, 8 * ms)
    assert_equal(x.count, 8)
    assert_equal(y.count, 4)
    run(1 * ms)
    assert_equal(c1.t, 9 * ms)
    assert_equal(c2.t, 10 * ms)
    assert_equal(x.count, 9)
    assert_equal(y.count, 5)
示例#21
0
def test_network_before_after_schedule():
    # Test that before... and after... slot names can be used
    NameLister.updates[:] = []
    x = NameLister(name='x', when='before_resets')
    y = NameLister(name='y', when='after_thresholds')
    net = Network(x, y)
    net.schedule = ['thresholds', 'resets']
    net.run(0.3*ms)
    assert_equal(''.join(NameLister.updates), 'yxyxyx')
示例#22
0
def test_network_different_clocks():
    NameLister.updates[:] = []
    # Check that a network with two different clocks functions correctly
    x = NameLister(name='x', dt=.1 * ms, order=0)
    y = NameLister(name='y', dt=1 * ms, order=1)
    net = Network(x, y)
    net.run(100 * second + defaultclock.dt, report='text')
    updates = ''.join(NameLister.updates)[2:]  # ignore the first time step
    assert updates == ('xxxxxxxxxxy' * 100000)
示例#23
0
def test_network_different_clocks():
    # Check that a network with two different clocks functions correctly
    clock1 = Clock(dt=1 * ms)
    clock3 = Clock(dt=3 * ms)
    x = NameLister(name='x', when=(clock1, 0))
    y = NameLister(name='y', when=(clock3, 1))
    net = Network(x, y)
    net.run(10 * ms)
    assert_equal(''.join(updates), 'xyxxxyxxxyxxxy')
示例#24
0
def test_continuation():
    defaultclock.dt = 1*ms
    G = NeuronGroup(1, 'dv/dt = -v / (10*ms) : 1')
    G.v = 1
    mon = StateMonitor(G, 'v', record=True)
    net = Network(G, mon)
    net.run(2*ms)

    # Run the same simulation but with two runs that use sub-dt run times
    G2 = NeuronGroup(1, 'dv/dt = -v / (10*ms) : 1')
    G2.v = 1
    mon2 = StateMonitor(G2, 'v', record=True)
    net2 = Network(G2, mon2)
    net2.run(0.5*ms)
    net2.run(1.5*ms)

    assert_equal(mon.t[:], mon2.t[:])
    assert_equal(mon.v[:], mon2.v[:])
示例#25
0
def test_defaultclock_dt_changes():
    BrianLogger.suppress_name('resolution_conflict')
    for dt in [0.1*ms, 0.01*ms, 0.5*ms, 1*ms, 3.3*ms]:
        defaultclock.dt = dt
        G = NeuronGroup(1, 'v:1')
        mon = StateMonitor(G, 'v', record=True)
        net = Network(G, mon)
        net.run(2*dt)
        assert_equal(mon.t[:], [0, dt/ms]*ms)
示例#26
0
def test_schedule_warning():
    previous_device = get_device()
    from uuid import uuid4

    # TestDevice1 supports arbitrary schedules, TestDevice2 does not
    class TestDevice1(Device):
        # These functions are needed during the setup of the defaultclock
        def get_value(self, var):
            return np.array([0.0001])

        def add_array(self, var):
            pass

        def init_with_zeros(self, var, dtype):
            pass

        def fill_with_array(self, var, arr):
            pass

    class TestDevice2(TestDevice1):
        def __init__(self):
            super(TestDevice2, self).__init__()
            self.network_schedule = [
                'start', 'groups', 'synapses', 'thresholds', 'resets', 'end'
            ]

    # Unique names are important for getting the warnings again for multiple
    # runs of the test suite
    name1 = 'testdevice_' + str(uuid4())
    name2 = 'testdevice_' + str(uuid4())
    all_devices[name1] = TestDevice1()
    all_devices[name2] = TestDevice2()

    set_device(name1)
    net = Network()
    # Any schedule should work
    net.schedule = list(reversed(net.schedule))
    with catch_logs() as l:
        net.run(0 * ms)
        assert len(l) == 0, 'did not expect a warning'

    set_device(name2)
    # Using the correct schedule should work
    net.schedule = [
        'start', 'groups', 'synapses', 'thresholds', 'resets', 'end'
    ]
    with catch_logs() as l:
        net.run(0 * ms)
        assert len(l) == 0, 'did not expect a warning'

    # Using another (e.g. the default) schedule should raise a warning
    net.schedule = None
    with catch_logs() as l:
        net.run(0 * ms)
        assert len(l) == 1 and l[0][1].endswith('schedule_conflict')
    reset_device(previous_device)
示例#27
0
def test_network_custom_slots():
    # Check that custom slots can be inserted into the schedule
    NameLister.updates[:] = []
    x = NameLister(name='x', when='thresholds')
    y = NameLister(name='y', when='in_between')
    z = NameLister(name='z', when='resets')
    net = Network(x, y, z)
    net.schedule = ['start', 'groups', 'thresholds', 'in_between', 'synapses', 'resets', 'end']
    net.run(0.3*ms)
    assert_equal(''.join(NameLister.updates), 'xyzxyzxyz')
示例#28
0
def test_multiple_runs_defaultclock_incorrect():
    defaultclock.dt = 0.1*ms
    G = NeuronGroup(1, 'dv/dt = -v / (10*ms) : 1')
    net = Network(G)
    net.run(0.5*ms)

    # The new dt is not compatible with the previous time since we cannot
    # continue at 0.5ms with a dt of 1ms
    defaultclock.dt = 1*ms
    assert_raises(ValueError, lambda: net.run(1*ms))
示例#29
0
def test_store_restore_to_file_differing_nets():
    # Check that the store/restore mechanism is not used with differing
    # networks
    filename = tempfile.mktemp(suffix='state', prefix='brian_test')

    source = SpikeGeneratorGroup(5, [0, 1, 2, 3, 4], [0, 1, 2, 3, 4] * ms,
                                 name='source_1')
    mon = SpikeMonitor(source, name='monitor')
    net = Network(source, mon)
    net.store(filename=filename)

    source_2 = SpikeGeneratorGroup(5, [0, 1, 2, 3, 4], [0, 1, 2, 3, 4] * ms,
                                   name='source_2')
    mon = SpikeMonitor(source_2, name='monitor')
    net = Network(source_2, mon)
    assert_raises(KeyError, lambda: net.restore(filename=filename))

    net = Network(source)  # Without the monitor
    assert_raises(KeyError, lambda: net.restore(filename=filename))
示例#30
0
def test_network_from_dict():
    # Check that a network from a dictionary works
    x = Counter()
    y = Counter()
    d = dict(a=x, b=y)
    net = Network()
    net.add(d)
    net.run(1 * ms)
    assert_equal(len(net.objects), 2)
    assert_equal(x.count, 10)
    assert_equal(y.count, 10)