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)
Ejemplo n.º 2
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))
Ejemplo n.º 3
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)
Ejemplo n.º 4
0
def run_old_algorithm(params, network_objs):
    monitors = network_objs["monitors"]
    network_objs.pop("monitors")
    network_objs.update(monitors)

    @network_operation(dt=params["rate_interval"], order=1)
    def local_update(t):
        if t/ms == 0:
            # if this is t = 0, skip the computation
            return
        firing_rates = network_objs["Pi"].A / (params["rate_interval"] / second)
        network_objs["Pi"].A = 0

        # apply the rate sensor to the single firing rates
        firing_rates = rate_sensor(firing_rates,
                                   params["x_NI"],
                                   params["sigma_s"])

        temp_w_holder = np.array(network_objs["con_ei"].w)
        for neuron_idx in np.arange(params["NI"]):
            delta_w = params["eta"] * (firing_rates[neuron_idx] - params["rho_0"])
            idxes = params["ei_conn_mat"][:,0] == neuron_idx
            temp_w_holder[idxes] += delta_w
        # set below 0 weights to zero.
        temp_w_holder = clip(temp_w_holder, params["wmin"], params["wmax"])
        network_objs["con_ei"].w = temp_w_holder

    network_objs["local_update"] = local_update
    net = Network(list(set(network_objs.values())))
    net.run(params["simtime"], report="stdout",
            profile= params["do_profiling"], namespace = params)
Ejemplo n.º 5
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))
Ejemplo n.º 6
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()))
Ejemplo n.º 7
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')
Ejemplo n.º 8
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_())
Ejemplo n.º 9
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')
Ejemplo n.º 10
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)
Ejemplo n.º 11
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 = Updater(name='x', when=(clock1, 0))
    y = Updater(name='y', when=(clock3, 1))
    net = Network(x, y)
    net.run(10*ms)
    assert_equal(''.join(updates), 'xyxxxyxxxyxxxy')
Ejemplo n.º 12
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)
Ejemplo n.º 13
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')
Ejemplo n.º 14
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)
    assert schedule_propagation_offset() == 0*ms
    net = Network()
    assert schedule_propagation_offset(net) == 0*ms

    # 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'

    assert schedule_propagation_offset(net) == defaultclock.dt

    set_device(name2)
    assert schedule_propagation_offset() == defaultclock.dt

    # 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'
    assert schedule_propagation_offset(net) == defaultclock.dt

    # 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)
Ejemplo n.º 15
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))
Ejemplo n.º 16
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')
Ejemplo n.º 17
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)
Ejemplo n.º 18
0
def test_network_reinit_prepare():
    # Check that reinit and prepare work        
    x = Preparer()
    net = Network(x)
    assert_equal(x.did_reinit, False)
    assert_equal(x.did_prepare, False)
    net.run(1*ms)
    assert_equal(x.did_reinit, False)
    assert_equal(x.did_prepare, True)
    net.reinit()
    assert_equal(x.did_reinit, True)
Ejemplo n.º 19
0
def test_network_two_objects():
    # Check that a network with two objects and the same clock function correctly
    x = Counter(order=5)
    y = Counter(order=6)
    net = Network()
    net.add([x, [y]]) # check that a funky way of adding objects work correctly
    assert_equal(net.objects[0].order, 5)
    assert_equal(net.objects[1].order, 6)
    assert_equal(len(net.objects), 2)
    net.run(1*ms)
    assert_equal(x.count, 10)
    assert_equal(y.count, 10)
Ejemplo n.º 20
0
def test_network_reinit_pre_post_run():
    # Check that reinit and before_run and after_run work
    x = Preparer()
    net = Network(x)
    assert_equal(x.did_reinit, False)
    assert_equal(x.did_pre_run, False)
    assert_equal(x.did_post_run, False)
    net.run(1*ms)
    assert_equal(x.did_reinit, False)
    assert_equal(x.did_pre_run, True)
    assert_equal(x.did_post_run, True)
    net.reinit()
    assert_equal(x.did_reinit, True)
Ejemplo n.º 21
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')
Ejemplo n.º 22
0
def create_cache(configuration):
    model_paths = load_model_paths()
    neuron_counts = _read_neuron_counts(configuration)
    hidden_layer = create_non_input_layer(model_paths, neuron_counts.hidden,
                                          'hidden')
    hidden_layer.Itau = get_current(15.3e-3) * amp
    number_of_output_neurons = 1
    layers_connected_to_output = _get_layers_connected_to_output_count(
        configuration)
    output_layer = create_non_input_layer(
        model_paths,
        number_of_output_neurons,
        'output',
        num_inputs=layers_connected_to_output)
    hidden_to_output_synapses = create_hidden_to_output_synapses(
        'main', hidden_layer, output_layer, model_paths, neuron_counts)

    input_layer = create_input_layer('main', neuron_counts.input)

    input_to_hidden_synapses = create_input_to_hidden_synapses(
        name='main',
        input_layer=input_layer,
        hidden_layer=hidden_layer,
        model_paths=model_paths,
        neuron_counts=neuron_counts)

    spike_monitors = SpikeMonitors(hidden=SpikeMonitor(hidden_layer),
                                   output=SpikeMonitor(output_layer))
    network = Network(input_layer, input_to_hidden_synapses, hidden_layer,
                      spike_monitors.hidden, spike_monitors.output,
                      output_layer, hidden_to_output_synapses)

    if should_add_artifact_filter(configuration):
        add_artifact_filter_to_network(model_paths, input_layer, output_layer,
                                       network)

    advanced_artifact_filter_input_layer = add_advanced_artifact_filter_to_network(
        network, output_layer, model_paths, neuron_counts
    ) if should_add_advanced_artifact_filter(configuration) else None

    network.store()

    return Cache(
        model_paths=model_paths,
        neuron_counts=neuron_counts,
        spike_monitors=spike_monitors,
        network=network,
        input_layer=input_layer,
        advanced_artifact_filter_input_layer=
        advanced_artifact_filter_input_layer,
    )
Ejemplo n.º 23
0
def test_synapse_connect_generator():
    # connector test 3
    start_scope()
    set_device('exporter', build_on_run=False)
    tau = 1 * ms
    eqn = 'dv/dt = (1 - v)/tau :1'
    Source = NeuronGroup(10, eqn, method='exact', threshold='v>0.9')
    S1 = Synapses(Source, Source)
    nett2 = Network(Source, S1)
    S1.connect(j='k for k in range(0, i+1)')
    nett2.run(1 * ms)
    connect3 = device.runs[0]['initializers_connectors'][0]
    assert connect3['j'] == 'k for k in range(0, i+1)'
    device.reinit()
Ejemplo n.º 24
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)

    del net
    defaultclock.t = 0 * second

    x = Stopper(10, stop)
    net = Network(x)
    net.run(10 * ms)
    assert_equal(defaultclock.t, 1 * ms)
Ejemplo n.º 25
0
def test_get_set_states():
    G = NeuronGroup(10, 'v:1', name='a_neurongroup')
    G.v = 'i'
    net = Network(G)
    states1 = net.get_states()
    states2 = magic_network.get_states()
    states3 = net.get_states(read_only_variables=False)
    assert set(states1.keys()) == set(states2.keys()) == set(states3.keys()) == {'a_neurongroup'}
    assert set(states1['a_neurongroup'].keys()) == set(states2['a_neurongroup'].keys()) == {'i', 'dt', 'N', 't', 'v'}
    assert set(states3['a_neurongroup']) == {'v'}

    # Try re-setting the state
    G.v = 0
    net.set_states(states3)
    assert_equal(G.v, np.arange(10))
Ejemplo n.º 26
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
Ejemplo n.º 27
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
Ejemplo n.º 28
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
Ejemplo n.º 29
0
def test_profile():
    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)
    # The should be four simulated CodeObjects, one for the group and one each
    # for state update, threshold and reset
    info = net.profiling_info
    info_dict = dict(info)
    assert len(info) == 4
    assert 'profile_test' in info_dict
    assert 'profile_test_stateupdater' in info_dict
    assert 'profile_test_thresholder' in info_dict
    assert 'profile_test_resetter' in info_dict
    assert all([t>=0*second for _, t in info])
Ejemplo n.º 30
0
    def __init__(
        self,
        model: str = "dv/dt = -v/(10*ms) : volt",
        threshold: str = "v > -50*mV",
        reset="v = -70*mV",
        refractory: str = "5*ms",
    ) -> None:
        self._fire_callbacks = []
        self._time_step_size_ms = 0.12

        self._group = NeuronGroup(1,
                                  model,
                                  threshold=threshold,
                                  reset=reset,
                                  refractory=refractory)
        self._monitor = StateMonitor(self._group, ("v", ), record=[0])
        self._net = Network(self._group, self._monitor)
Ejemplo n.º 31
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
Ejemplo n.º 32
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)
Ejemplo n.º 33
0
def test_network_remove():
    x = Counter()
    y = Counter()
    net = Network(x, y)
    net.remove(y)
    net.run(1*ms)
    assert_equal(x.count, 10)
    assert_equal(y.count, 0)
    # the relevance of this test is when we use weakref.proxy objects in
    # Network.objects, we should be able to add and remove these from
    # the Network just as much as the original objects
    # TODO: Does this test make sense now that Network does not store weak
    #       references by default?
    for obj in copy.copy(net.objects):
        net.remove(obj)
    net.run(1*ms)
    assert_equal(x.count, 10)
    assert_equal(y.count, 0)
Ejemplo n.º 34
0
def setup_standalone(request):
    # Workaround to avoid issues with Network instances still around
    Network.__instances__().clear()
    set_device('cpp_standalone', directory=None)
    dt = 0.1 * ms
    duration = 10 * ms
    neurons = NeuronGroup(1, model, name='neurons')
    monitor = StateMonitor(neurons, 'I', record=True, name='monitor')

    net = Network(neurons, monitor)

    def fin():
        reinit_devices()
        set_device('runtime')

    request.addfinalizer(fin)

    return net, dt, duration
	def brianNetwork(self):

		#/####################/#
		# init the Network
		#

		#maybe should import
		from brian2 import Network

		#set
		self.BrianedNetworkVariable=Network()

		#/####################/#
		# adapt dimension time
		#

		#Check
		if self.BrianingTimeDimensionVariable==None:

			from brian2 import ms 
			self.BrianingTimeDimensionVariable=ms

		#/####################/#
		# init a simulation clock
		#

		#debug
		self.debug(
			[
				'We set a simulation clock at least'
			]
		)

		#Check
		if 'Clocks' not in self.TeamDict:
			ClocksDeriveManager=self.team('Clocks').TeamedValueVariable
		else:
			ClocksDeriveManager=self.TeamDict['Clocks']

		#manage
		if 'Simulation' not in ClocksDeriveManager.ManagementDict:

			#debug
			self.debug(
				[
					'We init a simulation clock here'
				]
			)

			#manage
			SimulationDeriveBrianer=ClocksDeriveManager.manage(
				'Simulation',
				{
					'BrianingStepTimeFloat':self.BrianingStepTimeFloat
				}
			)
Ejemplo n.º 36
0
def test_synapse_connect_ij():
    # connector test 2
    start_scope()
    set_device('exporter', build_on_run=False)
    tau = 10 * ms
    eqn = 'dv/dt = (1 - v)/tau :1'
    my_prob = -1
    Source = NeuronGroup(10, eqn, method='exact', threshold='v>0.9')
    S1 = Synapses(Source, Source)
    nett = Network(Source, S1)
    S1.connect(i=[0, 1], j=[1, 2], p='my_prob')
    nett.run(1 * ms)
    connect2 = device.runs[0]['initializers_connectors'][0]
    assert connect2['i'] == [0, 1]
    assert connect2['j'] == [1, 2]
    assert connect2['identifiers']['my_prob'] == -1
    with pytest.raises(KeyError):
        connect2['condition']
    device.reinit()
Ejemplo n.º 37
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)
Ejemplo n.º 38
0
def test_network_access():
    x = Counter(name='counter')
    net = Network(x)
    assert len(net) == 1

    # accessing objects
    assert net['counter'] is x
    assert_raises(TypeError, lambda: net[123])
    assert_raises(TypeError, lambda: net[1:3])
    assert_raises(KeyError, lambda: net['non-existing'])

    objects = [obj for obj in net]
    assert set(objects) == set(net.objects)

    # deleting objects
    del net['counter']
    assert_raises(TypeError, lambda: net.__delitem__(123))
    assert_raises(TypeError, lambda: net.__delitem__(slice(1, 3)))
    assert_raises(KeyError, lambda: net.__delitem__('counter'))
Ejemplo n.º 39
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))
def setup_standalone(request):
    # Workaround to avoid issues with Network instances still around
    Network.__instances__().clear()
    set_device('cpp_standalone', directory=None)
    dt = 0.01 * ms
    tf = TraceFitter(dt=dt,
                     model=model,
                     input_var='v',
                     output_var='I',
                     input=input_traces,
                     output=output_traces,
                     n_samples=2)

    def fin():
        reinit_devices()
        set_device('runtime')
    request.addfinalizer(fin)

    return dt, tf
Ejemplo n.º 41
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)
Ejemplo n.º 42
0
def test_network_access():
    x = Counter(name='counter')
    net = Network(x)
    assert len(net) == 1

    # accessing objects
    assert net['counter'] is x
    assert_raises(TypeError, lambda: net[123])
    assert_raises(TypeError, lambda: net[1:3])
    assert_raises(KeyError, lambda: net['non-existing'])

    objects = [obj for obj in net]
    assert set(objects) == set(net.objects)

    # deleting objects
    del net['counter']
    assert_raises(TypeError, lambda: net.__delitem__(123))
    assert_raises(TypeError, lambda: net.__delitem__(slice(1, 3)))
    assert_raises(KeyError, lambda: net.__delitem__('counter'))
Ejemplo n.º 43
0
def test_network_remove():
    x = Counter()
    y = Counter()
    net = Network(x, y)
    net.remove(y)
    net.run(1*ms)
    assert_equal(x.count, 10)
    assert_equal(y.count, 0)
    # the relevance of this test is when we use weakref.proxy objects in
    # Network.objects, we should be able to add and remove these from
    # the Network just as much as the original objects
    for obj in copy.copy(net.objects):
        net.remove(obj)
    net.run(1*ms)
    assert_equal(x.count, 10)
    assert_equal(y.count, 0)
Ejemplo n.º 44
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))
Ejemplo n.º 45
0
def test_network_default_schedule():
    net = Network()
    assert net.schedule == [
        'start', 'groups', 'thresholds', 'synapses', 'resets', 'end'
    ]
    # Set the preference and check that the change is taken into account
    prefs.core.network.default_schedule = list(
        reversed(
            ['start', 'groups', 'thresholds', 'synapses', 'resets', 'end']))
    assert net.schedule == list(
        reversed(
            ['start', 'groups', 'thresholds', 'synapses', 'resets', 'end']))
def test_initialize_simulation_runtime(setup):
    net, dt, duration = setup
    start_scope()
    rts = RuntimeSimulator()
    assert_raises(TypeError, rts.initialize)

    rts.initialize(net, var_init=None)
    assert (isinstance(rts.networks['fit'], Network))
    assert_raises(KeyError, rts.initialize, empty_net, None)
    wrong_net = Network(NeuronGroup(1, model, name='neurons2'))
    assert_raises(Exception, rts.initialize, wrong_net, None)
    assert_raises(TypeError, rts.initialize, Network)
Ejemplo n.º 47
0
def test_initialize_simulation_standalone(setup):
    start_scope()
    net, _, _ = setup
    sas = CPPStandaloneSimulator()
    assert_raises(TypeError, sas.initialize)
    assert_raises(TypeError, sas.initialize, net)
    assert_raises(KeyError, sas.initialize, empty_net, None)
    wrong_net = Network(NeuronGroup(1, model, name='neurons2'))
    assert_raises(Exception, sas.initialize, wrong_net, None)

    sas.initialize(net, var_init=None, name='test')
    assert (isinstance(sas.networks['test'], Network))
Ejemplo n.º 48
0
def test_schedule_warning():
    previous_device = get_device()
    from uuid import uuid4
    # TestDevice1 supports arbitrary schedules, TestDevice2 does not
    class TestDevice1(Device):
        pass
    class TestDevice2(Device):
        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')
    set_device(previous_device)
def run_net(traj):
    """Creates and runs BRIAN network based on the parameters in `traj`."""

    eqs = traj.eqs

    # Create a namespace dictionairy
    namespace = traj.Net.f_to_dict(short_names=True, fast_access=True)
    # Create the Neuron Group
    neuron = NeuronGroup(traj.N,
                         model=eqs,
                         threshold=traj.Vcut,
                         reset=traj.reset,
                         namespace=namespace)
    neuron.vm = traj.EL
    neuron.w = traj.a * (neuron.vm - traj.EL)
    neuron.Vr = linspace(-48.3 * mV, -47.7 * mV,
                         traj.N)  # bifurcation parameter

    # Run the network initially for 100 milliseconds
    print('Initial Run')
    net = Network(neuron)
    net.run(100 * ms, report='text')  # we discard the first spikes

    # Create a Spike Monitor
    MSpike = SpikeMonitor(neuron)
    net.add(MSpike)
    # Create a State Monitor for the membrane voltage, record from neurons 1-3
    MStateV = StateMonitor(neuron, variables=['vm'], record=[1, 2, 3])
    net.add(MStateV)

    # Now record for 500 milliseconds
    print('Measurement run')
    net.run(500 * ms, report='text')

    # Add the BRAIN monitors
    traj.v_standard_result = Brian2MonitorResult
    traj.f_add_result('SpikeMonitor', MSpike)
    traj.f_add_result('StateMonitorV', MStateV)
Ejemplo n.º 50
0
def test_network_schedule_change():
    # Check that a changed schedule is taken into account correctly
    NameLister.updates[:] = []
    x = NameLister(name='x', when='thresholds')
    y = NameLister(name='y', when='resets')
    net = Network(x, y)
    net.run(0.3*ms)
    assert_equal(''.join(NameLister.updates), 'xyxyxy')
    NameLister.updates[:] = []
    net.schedule = ['start', 'groups', 'synapses', 'resets', 'thresholds', 'end']
    net.run(0.3*ms)
    assert_equal(''.join(NameLister.updates), 'yxyxyx')
Ejemplo n.º 51
0
def test_network_reinit_pre_post_run():
    # Check that reinit and before_run and after_run work
    x = Preparer()
    net = Network(x)
    assert_equal(x.did_reinit, False)
    assert_equal(x.did_pre_run, False)
    assert_equal(x.did_post_run, False)
    net.run(1 * ms)
    assert_equal(x.did_reinit, False)
    assert_equal(x.did_pre_run, True)
    assert_equal(x.did_post_run, True)
    net.reinit()
    assert_equal(x.did_reinit, True)

    # Make sure that running with "report" works
    net.run(1 * ms, report='stdout')
def test_run_simulation_runtime_var_init(setup):
    _, dt, duration = setup
    start_scope()

    neurons = NeuronGroup(1, model2, name='neurons')
    monitor = StateMonitor(neurons, 'v', record=True, name='statemonitor')
    net = Network(neurons, monitor)

    rts = RuntimeSimulator()
    rts.initialize(net, var_init={'v': -60 * mV})

    rts.run(duration, {'gL': 100, 'C': 10}, ['gL', 'C'], iteration=0)
    v = getattr(rts.statemonitor, 'v')
    assert_equal(np.shape(v), (1, duration / dt))
Ejemplo n.º 53
0
    def setup_simulator(self,
                        network_name,
                        n_neurons,
                        output_var,
                        param_init,
                        calc_gradient=False,
                        optimize=True,
                        online_error=False,
                        level=1):
        simulator = setup_fit()

        namespace = get_full_namespace(
            {
                'input_var': self.input_traces,
                'n_traces': self.n_traces
            },
            level=level + 1)
        if hasattr(self, 't_start'):  # OnlineTraceFitter
            namespace['t_start'] = self.t_start
        if network_name != 'generate' and self.output_var != 'spikes':
            namespace['output_var'] = TimedArray(self.output.transpose(),
                                                 dt=self.dt)
        neurons = self.setup_neuron_group(n_neurons,
                                          namespace,
                                          calc_gradient=calc_gradient,
                                          optimize=optimize,
                                          online_error=online_error)

        if output_var == 'spikes':
            monitor = SpikeMonitor(neurons, name='monitor')
        else:
            record_vars = [output_var]
            if calc_gradient:
                record_vars.extend(
                    [f'S_{output_var}_{p}' for p in self.parameter_names])
            monitor = StateMonitor(neurons,
                                   record_vars,
                                   record=True,
                                   name='monitor',
                                   dt=self.dt)

        network = Network(neurons, monitor)

        if calc_gradient:
            param_init = dict(param_init)
            param_init.update(
                get_sensitivity_init(neurons, self.parameter_names,
                                     param_init))
        simulator.initialize(network, param_init, name=network_name)
        return simulator
Ejemplo n.º 54
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)
Ejemplo n.º 55
0
def test_network_incorrect_schedule():
    # Test that incorrect arguments provided to schedule raise errors
    net = Network()
    # net.schedule = object()
    assert_raises(TypeError, setattr, net, 'schedule', object())
    # net.schedule = 1
    assert_raises(TypeError, setattr, net, 'schedule', 1)
    # net.schedule = {'slot1', 'slot2'}
    assert_raises(TypeError, setattr, net, 'schedule', {'slot1', 'slot2'})
    # net.schedule = ['slot', 1]
    assert_raises(TypeError, setattr, net, 'schedule', ['slot', 1])
    # net.schedule = ['start', 'after_start']
    assert_raises(ValueError, setattr, net, 'schedule', ['start', 'after_start'])
    # net.schedule = ['before_start', 'start']
    assert_raises(ValueError, setattr, net, 'schedule', ['before_start', 'start'])
Ejemplo n.º 56
0
def setup(request):
    dt = 0.1 * ms
    duration = 10 * ms

    neurons = NeuronGroup(1, model, name='neurons')
    monitor = StateMonitor(neurons, 'I', record=True, name='statemonitor')

    net = Network(neurons, monitor)

    def fin():
        reinit_devices()

    request.addfinalizer(fin)

    return net, dt, duration
Ejemplo n.º 57
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[:])