def test_refractoriness_variables(): # Try a string evaluating to a quantity an an explicit boolean # condition -- all should do the same thing for ref_time in [ '5*ms', '(t-lastspike + 1e-3*dt) < 5*ms', 'time_since_spike + 1e-3*dt < 5*ms', 'ref_subexpression', '(t-lastspike + 1e-3*dt) <= ref', 'ref', 'ref_no_unit*ms' ]: reinit_and_delete() G = NeuronGroup(1, ''' dv/dt = 99.999*Hz : 1 (unless refractory) dw/dt = 99.999*Hz : 1 ref : second ref_no_unit : 1 time_since_spike = (t - lastspike) +1e-3*dt : second ref_subexpression = (t - lastspike + 1e-3*dt) < ref : boolean ''', threshold='v>1', reset='v=0;w=0', refractory=ref_time, dtype={ 'ref': defaultclock.variables['t'].dtype, 'ref_no_unit': defaultclock.variables['t'].dtype, 'lastspike': defaultclock.variables['t'].dtype, 'time_since_spike': defaultclock.variables['t'].dtype }) G.ref = 5 * ms G.ref_no_unit = 5 # It should take 10ms to reach the threshold, then v should stay at 0 # for 5ms, while w continues to increase mon = StateMonitor(G, ['v', 'w'], record=True, when='end') run(20 * ms) try: # No difference before the spike assert_allclose(mon[0].v[:timestep(10 * ms, defaultclock.dt)], mon[0].w[:timestep(10 * ms, defaultclock.dt)]) # v is not updated during refractoriness in_refractoriness = mon[0].v[timestep(10 * ms, defaultclock.dt): timestep(15 * ms, defaultclock.dt)] assert_allclose(in_refractoriness, np.zeros_like(in_refractoriness)) # w should evolve as before assert_allclose( mon[0].w[:timestep(5 * ms, defaultclock.dt)], mon[0].w[timestep(10 * ms, defaultclock.dt) + 1:timestep(15 * ms, defaultclock.dt) + 1]) assert np.all( mon[0].w[timestep(10 * ms, defaultclock.dt) + 1:timestep(15 * ms, defaultclock.dt) + 1] > 0) # After refractoriness, v should increase again assert np.all( mon[0].v[timestep(15 * ms, defaultclock.dt ):timestep(20 * ms, defaultclock.dt)] > 0) except AssertionError as ex: raise raise AssertionError( 'Assertion failed when using %r as refractory argument:\n%s' % (ref_time, ex))
def test_refractoriness_threshold(): # Try a quantity, a string evaluating to a quantity an an explicit boolean # condition -- all should do the same thing for ref_time in [ 10 * ms, '10*ms', '(t-lastspike) <= 10*ms', '(t-lastspike) <= ref', 'ref', 'ref_no_unit*ms' ]: reinit_and_delete() G = NeuronGroup(1, ''' dv/dt = 199.99*Hz : 1 ref : second ref_no_unit : 1 ''', threshold='v > 1', reset='v=0', refractory=ref_time, dtype={ 'ref': defaultclock.variables['t'].dtype, 'ref_no_unit': defaultclock.variables['t'].dtype }) G.ref = 10 * ms G.ref_no_unit = 10 # The neuron should spike after 5ms but then not spike for the next # 10ms. The state variable should continue to integrate so there should # be a spike after 15ms spike_mon = SpikeMonitor(G) run(16 * ms) assert_allclose(spike_mon.t, [5, 15] * ms)
def pytest_runtest_makereport(item, call): if hasattr(item.config, 'slaveinput'): fail_for_not_implemented = item.config.slaveinput['fail_for_not_implemented'] else: fail_for_not_implemented = item.config.fail_for_not_implemented outcome = yield rep = outcome.get_result() if rep.outcome == 'failed': reinit_devices() if not fail_for_not_implemented: if call.excinfo.errisinstance(NotImplementedError): rep.outcome = 'skipped' r = call.excinfo._getreprcrash() rep.longrepr = (str(r.path), r.lineno, r.message) else: # clean up after the test (delete directory for standalone) reinit_and_delete()
def pytest_runtest_makereport(item, call): if hasattr(item.config, 'workerinput'): fail_for_not_implemented = item.config.workerinput['fail_for_not_implemented'] else: fail_for_not_implemented = item.config.fail_for_not_implemented outcome = yield rep = outcome.get_result() if rep.outcome == 'failed': project_dir = getattr(get_device(), 'project_dir', None) if project_dir is not None: rep.sections.append(('Standalone project directory', f'{project_dir}')) reinit_devices() if not fail_for_not_implemented: exc_cause = getattr(call.excinfo.value, '__cause__', None) if (call.excinfo.errisinstance(NotImplementedError) or isinstance(exc_cause, NotImplementedError)): rep.outcome = 'skipped' r = call.excinfo._getreprcrash() rep.longrepr = (str(r.path), r.lineno, r.message) else: # clean up after the test (delete directory for standalone) reinit_and_delete()
def setup_and_teardown(request): # Set preferences before each test import brian2 if hasattr(request.config, 'slaveinput'): for key, value in request.config.slaveinput['brian_prefs'].items(): if isinstance(value, tuple) and value[0] == 'TYPE': matches = re.match(r"<(type|class) 'numpy\.(.+)'>", value[1]) if matches is None or len(matches.groups()) != 2: raise TypeError('Do not know how to handle {} in ' 'preferences'.format(value[1])) t = matches.groups()[1] if t == 'float64': value = np.float64 elif t == 'float32': value = np.float32 elif t == 'int64': value = np.int64 elif t == 'int32': value = np.int32 brian2.prefs[key] = value else: for k, v in request.config.brian_prefs.items(): brian2.prefs[k] = v brian2.prefs._backup() # Print output changed in numpy 1.14, stick with the old format to # avoid doctest failures try: np.set_printoptions(legacy='1.13') except TypeError: pass # using a numpy version < 1.14 yield # run test # clean up after the test reinit_and_delete() # Reset defaultclock.dt to be sure defaultclock.dt = 0.1 * ms
with pytest.raises(BrianObjectException) as exc: net.run(0 * ms) assert exc_isinstance(exc, NotImplementedError) defaultclock.dt = old_dt @pytest.mark.standalone_compatible def test_poissoninput_refractory(): eqs = """ dv/dt = 0/second : 1 (unless refractory) """ G = NeuronGroup(10, eqs, reset='v=0', threshold='v>4.5', refractory=5 * defaultclock.dt) # Will increase the value by 1.0 at each time step P = PoissonInput(G, 'v', 1, 1 / defaultclock.dt, weight=1.0) mon = StateMonitor(G, 'v', record=5) run(10 * defaultclock.dt) expected = np.arange(10, dtype=float) expected[6 - int(schedule_propagation_offset() / defaultclock.dt):] = 0 assert_allclose(mon[5].v[:], expected) if __name__ == '__main__': test_poissoninput() reinit_and_delete() test_poissoninput_errors() test_poissoninput_refractory()
def test_openmp_consistency(): previous_device = get_device() n_cells = 100 n_recorded = 10 numpy.random.seed(42) taum = 20 * ms taus = 5 * ms Vt = -50 * mV Vr = -60 * mV El = -49 * mV fac = (60 * 0.27 / 10) gmax = 20 * fac dApre = .01 taupre = 20 * ms taupost = taupre dApost = -dApre * taupre / taupost * 1.05 dApost *= 0.1 * gmax dApre *= 0.1 * gmax connectivity = numpy.random.randn(n_cells, n_cells) sources = numpy.random.randint(0, n_cells - 1, 10 * n_cells) # Only use one spike per time step (to rule out that a single source neuron # has more than one spike in a time step) times = numpy.random.choice( numpy.arange(10 * n_cells), 10 * n_cells, replace=False) * ms v_init = Vr + numpy.random.rand(n_cells) * (Vt - Vr) eqs = Equations(''' dv/dt = (g-(v-El))/taum : volt dg/dt = -g/taus : volt ''') results = {} for (n_threads, devicename) in [(0, 'runtime'), (0, 'cpp_standalone'), (1, 'cpp_standalone'), (2, 'cpp_standalone'), (3, 'cpp_standalone'), (4, 'cpp_standalone')]: set_device(devicename, build_on_run=False, with_output=False) Synapses.__instances__().clear() if devicename == 'cpp_standalone': reinit_and_delete() prefs.devices.cpp_standalone.openmp_threads = n_threads P = NeuronGroup(n_cells, model=eqs, threshold='v>Vt', reset='v=Vr', refractory=5 * ms) Q = SpikeGeneratorGroup(n_cells, sources, times) P.v = v_init P.g = 0 * mV S = Synapses(P, P, model='''dApre/dt=-Apre/taupre : 1 (event-driven) dApost/dt=-Apost/taupost : 1 (event-driven) w : 1''', pre='''g += w*mV Apre += dApre w = w + Apost''', post='''Apost += dApost w = w + Apre''') S.connect() S.w = fac * connectivity.flatten() T = Synapses(Q, P, model="w : 1", on_pre="g += w*mV") T.connect(j='i') T.w = 10 * fac spike_mon = SpikeMonitor(P) rate_mon = PopulationRateMonitor(P) state_mon = StateMonitor(S, 'w', record=np.arange(n_recorded), dt=0.1 * second) v_mon = StateMonitor(P, 'v', record=np.arange(n_recorded)) run(0.2 * second, report='text') if devicename == 'cpp_standalone': device.build(directory=None, with_output=False) results[n_threads, devicename] = {} results[n_threads, devicename]['w'] = state_mon.w results[n_threads, devicename]['v'] = v_mon.v results[n_threads, devicename]['s'] = spike_mon.num_spikes results[n_threads, devicename]['r'] = rate_mon.rate[:] for key1, key2 in [((0, 'runtime'), (0, 'cpp_standalone')), ((1, 'cpp_standalone'), (0, 'cpp_standalone')), ((2, 'cpp_standalone'), (0, 'cpp_standalone')), ((3, 'cpp_standalone'), (0, 'cpp_standalone')), ((4, 'cpp_standalone'), (0, 'cpp_standalone'))]: assert_allclose(results[key1]['w'], results[key2]['w']) assert_allclose(results[key1]['v'], results[key2]['v']) assert_allclose(results[key1]['r'], results[key2]['r']) assert_allclose(results[key1]['s'], results[key2]['s']) reset_device(previous_device)