예제 #1
0
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_devices()
        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)
예제 #2
0
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_devices()
        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_sorted_indices_statemonitor():
    previous_device = get_device()

    results = {}

    n_cells = 5
    n_recorded = 10
    delay = np.arange(n_cells) * defaultclock.dt

    for devicename in ['cpp_standalone', 'cuda_standalone']:
        set_device(devicename, build_on_run=False, with_output=False)
        Synapses.__instances__().clear()
        reinit_devices()
        P = NeuronGroup(n_cells, model='', threshold='True')
        S = Synapses(P, P, model='''w : 1''', on_pre='''w += 1''')
        S.connect(j='i')
        S.pre.delay = delay

        state_mon = StateMonitor(S, 'w', record=range(n_recorded))

        run(defaultclock.dt * (n_cells + 1))

        device.build(directory=None, with_output=False)
        results[devicename] = state_mon.w.astype(int)

    assert_allclose(results['cpp_standalone'].sum(axis=0),
                    results['cuda_standalone'].sum(axis=0))
    assert_allclose(results['cpp_standalone'], results['cuda_standalone'])

    reset_device(previous_device)
예제 #4
0
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) <= 5*ms', 'time_since_spike <= 5*ms',
            'ref_subexpression', '(t-lastspike) <= ref', 'ref',
            'ref_no_unit*ms'
    ]:
        reinit_devices()
        G = NeuronGroup(1,
                        '''
                        dv/dt = 100*Hz : 1 (unless refractory)
                        dw/dt = 100*Hz : 1
                        ref : second
                        ref_no_unit : 1
                        time_since_spike = t - lastspike : second
                        ref_subexpression = (t - lastspike) <= ref : boolean
                        ''',
                        threshold='v>1',
                        reset='v=0;w=0',
                        refractory=ref_time)
        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_equal(mon[0].v[mon.t < 10 * ms], mon[0].w[mon.t < 10 * ms])
            # v is not updated during refractoriness
            in_refractoriness = mon[0].v[(mon.t >= 10 * ms)
                                         & (mon.t < 15 * ms)]
            assert_equal(in_refractoriness, np.zeros_like(in_refractoriness))
            # w should evolve as before
            assert_equal(mon[0].w[mon.t < 5 * ms],
                         mon[0].w[(mon.t >= 10 * ms) & (mon.t < 15 * ms)])
            assert np.all(mon[0].w[(mon.t >= 10 * ms) & (mon.t < 15 * ms)] > 0)
            # After refractoriness, v should increase again
            assert np.all(mon[0].v[(mon.t >= 15 * ms) & (mon.t < 20 * ms)] > 0)
        except AssertionError as ex:
            raise AssertionError(
                'Assertion failed when using %r as refractory argument:\n%s' %
                (ref_time, ex))
예제 #5
0
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_devices()
        G = NeuronGroup(1, '''
                        dv/dt = 200*Hz : 1
                        ref : second
                        ref_no_unit : 1
                        ''', threshold='v > 1',
                        reset='v=0', refractory=ref_time)
        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, [4.9, 15] * ms)
예제 #6
0
def generate_results(num_repeats):
    results = {}

    for name in ['CUBA', 'COBA']:
        for target in ['numpy', 'cython', 'weave']:
            for dtype in [float32, float64]:
                prefs.codegen.target = target
                prefs.core.default_float_dtype = dtype
                times = [run_benchmark(name) for repeat in range(num_repeats)]
                results[name, target, dtype.__name__] = amin(times)

    for name in ['CUBA', 'COBA']:
        for dtype in [float32, float64]:
            times = []
            for _ in range(num_repeats):
                reset_device()
                reinit_devices()
                set_device('cpp_standalone', directory=None, with_output=False)
                prefs.core.default_float_dtype = dtype
                times.append(run_benchmark(name))
            results[name, 'cpp_standalone', dtype.__name__] = amin(times)

    return results
예제 #7
0
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) <= 5*ms',
                     'time_since_spike <= 5*ms', 'ref_subexpression',
                     '(t-lastspike) <= ref', 'ref', 'ref_no_unit*ms']:
        reinit_devices()
        G = NeuronGroup(1, '''
                        dv/dt = 100*Hz : 1 (unless refractory)
                        dw/dt = 100*Hz : 1
                        ref : second
                        ref_no_unit : 1
                        time_since_spike = t - lastspike : second
                        ref_subexpression = (t - lastspike) <= ref : boolean
                        ''',
                        threshold='v>1', reset='v=0;w=0',
                        refractory=ref_time)
        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_equal(mon[0].v[mon.t < 10*ms], mon[0].w[mon.t < 10*ms])
            # v is not updated during refractoriness
            in_refractoriness = mon[0].v[(mon.t >= 10*ms) & (mon.t <15*ms)]
            assert_equal(in_refractoriness, np.zeros_like(in_refractoriness))
            # w should evolve as before
            assert_equal(mon[0].w[mon.t < 5*ms], mon[0].w[(mon.t >= 10*ms) & (mon.t <15*ms)])
            assert np.all(mon[0].w[(mon.t >= 10*ms) & (mon.t <15*ms)] > 0)
            # After refractoriness, v should increase again
            assert np.all(mon[0].v[(mon.t >= 15*ms) & (mon.t <20*ms)] > 0)
        except AssertionError as ex:
            raise AssertionError('Assertion failed when using %r as refractory argument:\n%s' % (ref_time, ex))
예제 #8
0
    net = Network(collect())
    assert_raises(NotImplementedError, lambda: net.run(0 * ms))
    defaultclock.dt = old_dt


@attr('standalone-compatible')
@with_setup(teardown=reinit_devices)
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=np.float)
    expected[6 - int(schedule_propagation_offset() / defaultclock.dt):] = 0
    assert_allclose(mon[5].v[:], expected)


if __name__ == '__main__':
    test_poissoninput()
    reinit_devices()
    test_poissoninput_errors()
    test_poissoninput_refractory()
예제 #9
0
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.random_integers(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_devices()
        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=range(n_recorded), dt=0.1*second)
        v_mon     = StateMonitor(P, 'v', record=range(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)
def simple_model(N,
                 params,
                 record=None,
                 update_progress=None,
                 fm=None,
                 minimum_initial_time=100 * ms,
                 use_standalone_openmp=False):
    if use_standalone_openmp:
        prefs.devices.cpp_standalone.openmp_threads = multiprocessing.cpu_count(
        ) / 2  # assume hyperthreading
        set_device('cpp_standalone', with_output=True)
    seed(3402348923)  # for reproducibility
    if fm is None:
        fm = dietz_fm
    orig_fm = fm
    min_tauihc = 0.1 * ms
    eqs = '''
    carrier = clip(cos(2*pi*fc*t), 0, Inf) : 1
    A_raw = (carrier*gain*0.5*(1-cos(2*pi*fm*t)))**gamma : 1
    dA_filt/dt = (A_raw-A)/(int(tauihc<min_tauihc)*1*second+tauihc) : 1
    A = A_raw*int(tauihc<min_tauihc)+A_filt*int(tauihc>=min_tauihc) : 1
    dQ/dt = -k*Q*A+R*(1-Q) : 1
    AQ = A*Q : 1
    dAe/dt = (AQ-Ae)/taue : 1
    dAi/dt = (AQ-Ai)/taui : 1
    out = clip(Ae-beta*Ai, 0, Inf) : 1
    gain = 10**(level/20.) : 1
    R = (1-alpha)/taua : Hz
    k = alpha/taua : Hz
    fc = fc_Hz*Hz : Hz
    fc_Hz : 1
    fm : Hz
    tauihc = tauihc_ms*ms : second
    taue = taue_ms*ms : second
    taui = taui_ms*ms : second
    taua = taua_ms*ms : second
    tauihc_ms : 1
    taue_ms : 1
    taui_ms : 1
    taua_ms : 1
    alpha : 1
    beta : 1
    gamma : 1
    level : 1
    # Accumulation variables
    start_time : second
    end_time : second
    do_accumulate = 1.0*int(t>=start_time and t<end_time) : 1
    accum_sum_out : 1
    accum_sum_out_rising : 1
    accum_sum_out_falling : 1
    accum_argmax_out : second
    accum_max_out : 1
    accum_weighted_sum_cos_phase : 1
    accum_weighted_sum_sin_phase : 1
    '''
    G = NeuronGroup(N * len(fm), eqs, method='euler', dt=0.1 * ms)
    rr = G.run_regularly('''
        accum_sum_out += out*do_accumulate
        phase = (2*pi*fm*t)%(2*pi)
        accum_sum_out_rising += out*int(phase<pi)*do_accumulate
        accum_sum_out_falling += out*int(phase>=pi)*do_accumulate
        accum_weighted_sum_cos_phase += out*cos(phase)*do_accumulate
        accum_weighted_sum_sin_phase += out*sin(phase)*do_accumulate
        is_larger = out>accum_max_out and do_accumulate>0
        accum_max_out = int(not is_larger)*accum_max_out+int(is_larger)*out
        accum_argmax_out = int(not is_larger)*accum_argmax_out+int(is_larger)*t
        ''',
                         when='end')
    params = params.copy()
    for k, v in params.items():
        if isinstance(v, tuple) and len(v) == 2:
            low, high = v
            params[k] = v = rand(N) * (high - low) + low
    params2d = params.copy()
    for k, v in params2d.items():
        if isinstance(v, ndarray) and v.size > 1:
            v = reshape(v, v.size)
            fm, v = meshgrid(orig_fm,
                             v)  # fm and v have shape (N, len(dietz_fm))
            fm.shape = fm.size
            v.shape = v.size
            params2d[k] = v
    params2d['fm'] = fm
    G.set_states(params2d)
    G.tauihc_ms['tauihc_ms<min_tauihc/ms'] = 0
    G.Q = 1
    net = Network(G, rr)
    # Calculate how long to run the simulation
    period = 1 / fm
    num_initial_cycles = ceil(
        minimum_initial_time /
        period)  # at least one period and at least that time
    start_time = num_initial_cycles * period
    end_time = (num_initial_cycles + 1) * period
    duration = amax(end_time)
    G.start_time = start_time
    G.end_time = end_time
    # Run the simulation
    if isinstance(update_progress, basestring):
        report_period = 10 * second
    else:
        report_period = 1 * second
    if record:
        M = StateMonitor(G, record, record=True)
        net.add(M)
    net.run(duration, report=update_progress, report_period=report_period)
    G.accum_sum_out['accum_sum_out<1e-10'] = 1
    for name in [
            'accum_sum_out_rising', 'accum_sum_out_falling',
            'accum_argmax_out', 'accum_max_out',
            'accum_weighted_sum_cos_phase', 'accum_weighted_sum_sin_phase'
    ]:
        if name == 'accum_argmax_out':
            u = second
        else:
            u = 1
        getattr(G, name)['accum_sum_out>1e10'] = 0 * u
    G.accum_sum_out['accum_sum_out>1e10'] = 1
    c = G.accum_weighted_sum_cos_phase[:]
    s = G.accum_weighted_sum_sin_phase[:]
    weighted_phase = (angle(c + 1j * s) + 2 * pi) % (2 * pi)
    vs = sqrt(c**2 + s**2) / G.accum_sum_out[:]
    mean_fr = G.accum_sum_out[:] / ((end_time - start_time) / G.dt)
    onsettiness = 0.5 * (1 + (G.accum_sum_out_rising[:] -
                              G.accum_sum_out_falling[:]) / G.accum_sum_out[:])
    res = Results(
        accum_argmax_out=G.accum_argmax_out[:],
        accum_max_out=G.accum_max_out[:],
        weighted_phase=weighted_phase,
        vs=vs,
        mean_fr=mean_fr,
        onsettiness=onsettiness,
        params=params,
        start_time=start_time,
        end_time=end_time,
    )
    if record:
        for name in record:
            v = getattr(M, name)[:, :]
            v.shape = (N, len(dietz_fm), -1)
            setattr(res, name, v)
        res.t = M.t[:]
    if use_standalone_openmp:
        reset_device()
        reinit_devices()
    return res
예제 #11
0
            test_magic_collect,
            test_progress_report,
            test_progress_report_incorrect,
            test_multiple_runs_report_standalone,
            test_multiple_runs_report_standalone_2,
            test_multiple_runs_report_standalone_3,
            test_multiple_runs_report_standalone_incorrect,
            test_store_restore,
            test_store_restore_to_file,
            test_store_restore_to_file_new_objects,
            test_store_restore_to_file_differing_nets,
            test_store_restore_magic,
            test_store_restore_magic_to_file,
            test_defaultclock_dt_changes,
            test_dt_changes_between_runs,
            test_dt_restore,
            test_continuation,
            test_get_set_states,
            test_multiple_runs_defaultclock,
            test_multiple_runs_defaultclock_incorrect,
            test_profile,
            test_profile_ipython_html,
            test_magic_scope,
            test_runtime_rounding,
            test_small_runs,
            test_long_run_dt_change,
            ]:
        set_device(all_devices['runtime'])
        t()
        reinit_devices()
예제 #12
0
 def fin():
     reinit_devices()
     set_device('runtime')
예제 #13
0
 def fin():
     reinit_devices()
예제 #14
0
def test_openmp_consistency(with_output=False):
    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.random_integers(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_devices()
        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=range(n_recorded), dt=0.1*second)
        v_mon     = StateMonitor(P, 'v', record=range(n_recorded))

        run(0.2 * second, report='text')

        if devicename=='cpp_standalone':
            tempdir = tempfile.mkdtemp()
            if with_output:
                print tempdir
            device.build(directory=tempdir, compile=True,
                         run=True, with_output=with_output)

        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)