Esempio n. 1
0
def setup(timestep=0.1, min_delay=0.1, max_delay=10.0, **extra_params):
    """
    Should be called at the very beginning of a script.
    extra_params contains any keyword arguments that are required by a given
    simulator but not by others.
    """
    common.setup(timestep, min_delay, max_delay, **extra_params)
    simulator.state.clear()
    brian.set_global_preferences(**extra_params)
    simulator.state.dt = timestep  # move to common.setup?
    simulator.state.min_delay = min_delay
    simulator.state.max_delay = max_delay
    simulator.state.mpi_rank = extra_params.get('rank', 0)
    simulator.state.num_processes = extra_params.get('num_processes', 1)
    simulator.state.network.add(update_currents)
    update_currents.clock = simulator.state.network.clock
    return rank()
Esempio n. 2
0
def setup(timestep=0.1, min_delay=0.1, max_delay=10.0, **extra_params):
    """
    Should be called at the very beginning of a script.
    extra_params contains any keyword arguments that are required by a given
    simulator but not by others.
    """
    common.setup(timestep, min_delay, max_delay, **extra_params)
    simulator.state.clear()
    brian.set_global_preferences(**extra_params)
    simulator.state.dt = timestep  # move to common.setup?
    simulator.state.min_delay = min_delay
    simulator.state.max_delay = max_delay
    simulator.state.mpi_rank = extra_params.get('rank', 0)
    simulator.state.num_processes = extra_params.get('num_processes', 1)
    simulator.state.network.add(update_currents)
    update_currents.clock = simulator.state.network.clock
    return rank()
            locals()[var] = False
        else:
            raise Exception(
                'Expecting True or False-valued command line argument "' +
                var + '".')

    num_examples = num_test
    data_size = 10000

    # set brian global preferences
    b.set_global_preferences(defaultclock=b.Clock(dt=0.5 * b.ms),
                             useweave=True,
                             gcc_options=['-ffast-math -march=native'],
                             usecodegen=True,
                             usecodegenweave=True,
                             usecodegenstateupdate=True,
                             usecodegenthreshold=False,
                             usenewpropagate=True,
                             usecstdp=True,
                             openmp=False,
                             magic_useframes=False,
                             useweave_linear_diffeq=True)

    # for reproducibility's sake
    np.random.seed(random_seed)

    start = timeit.default_timer()
    data = get_labeled_data(os.path.join(MNIST_data_path, 'testing'), False,
                            False, xrange(10), 1000, normalize_inputs)

    print 'Time needed to load data:', timeit.default_timer() - start
from datetime import time

import brian

from perceptchoice.model.monitor import WTAMonitor


brian.set_global_preferences(useweave=True,openmp=True,useweave_linear_diffeq =True,
                             gcc_options = ['-ffast-math','-march=native'],usecodegenweave = True,
                             usecodegenreset = True)
from brian.library.IF import exp_IF
from brian.library.synapses import exp_synapse, biexp_synapse
from brian.membrane_equations import Current, InjectedCurrent
from brian.network import Network, network_operation
from brian.neurongroup import NeuronGroup
from brian.stdunits import pF, nS, mV, ms, Hz, pA, nF
from brian.tools.parameters import Parameters
from brian.units import siemens, second
from brian.clock import defaultclock, Clock
from brian.directcontrol import PoissonGroup
from brian.equations import Equations
from brian.connections import DelayConnection, Connection
import numpy as np
from numpy.matlib import randn, rand


pyr_params=Parameters(
    C=0.5*nF,
    gL=25*nS,
    refractory=2*ms,
    w_nmda = 0.165 * nS,
Esempio n. 5
0
from brian.library.IF import exp_IF
from brian.library.synapses import exp_synapse, biexp_synapse
from brian.membrane_equations import Current, InjectedCurrent
from brian.network import Network, network_operation
from brian.neurongroup import NeuronGroup
from brian.stdunits import pF, nS, mV, ms, Hz, pA, nF
from brian.tools.parameters import Parameters
from brian.units import siemens, second
import argparse
import numpy as np
from pysbi.util.utils import init_connection
from pysbi.voxel import Voxel, LFPSource, get_bold_signal
from pysbi.wta.monitor import WTAMonitor
brian.set_global_preferences(useweave=True,
                             openmp=True,
                             useweave_linear_diffeq=True,
                             gcc_options=['-ffast-math', '-march=native'],
                             usecodegenweave=True,
                             usecodegenreset=True)

pyr_params = Parameters(
    C=0.5 * nF,
    gL=25 * nS,
    refractory=2 * ms,
    w_nmda=0.165 * nS,
    w_ampa_ext_correct=2.1 * nS,
    w_ampa_ext_incorrect=0.0 * nS,
    w_ampa_bak=2.1 * nS,
    w_ampa_rec=0.05 * nS,
    w_gaba=1.3 * nS,
)
#------------------------------------------------------------------------------

b.set_global_preferences(
    defaultclock=b.Clock(
        dt=0.5 * b.ms
    ),  # The default clock to use if none is provided or defined in any enclosing scope.
    useweave=
    True,  # Defines whether or not functions should use inlined compiled C code where defined.
    gcc_options=[
        '-ffast-math -march=native'
    ],  # Defines the compiler switches passed to the gcc compiler. 
    #For gcc versions 4.2+ we recommend using -march=native. By default, the -ffast-math optimizations are turned on
    usecodegen=
    True,  # Whether or not to use experimental code generation support.
    usecodegenweave=
    True,  # Whether or not to use C with experimental code generation support.
    usecodegenstateupdate=
    True,  # Whether or not to use experimental code generation support on state updaters.
    usecodegenthreshold=
    False,  # Whether or not to use experimental code generation support on thresholds.
    usenewpropagate=
    True,  # Whether or not to use experimental new C propagation functions.
    usecstdp=True,  # Whether or not to use experimental new C STDP.
    openmp=True,  # whether or not to use OpenMP pragmas in generated C code.
    magic_useframes=
    True,  # defines whether or not the magic functions should serach for objects defined only in the calling frame,
    # or if they should find all objects defined in any frame. Set to "True" if not in an interactive shell.
    useweave_linear_diffeq=
    True,  # Whether to use weave C++ acceleration for the solution of linear differential equations.
)

np.random.seed(0)
testing = get_labeled_data(MNIST_data_path + 'testing', bTrain = False)
end = time.time()
print 'time needed to load test set:', end - start


#------------------------------------------------------------------------------
# set parameters and equations
#------------------------------------------------------------------------------
test_mode = True

b.set_global_preferences(
                        defaultclock = b.Clock(dt=0.5*b.ms), # The default clock to use if none is provided or defined in any enclosing scope.
                        useweave = True, # Defines whether or not functions should use inlined compiled C code where defined.
                        gcc_options = ['-march=native'],  # Defines the compiler switches passed to the gcc compiler.
                        #For gcc versions 4.2+ we recommend using -march=native. By default, the -ffast-math optimizations are turned on
                        usecodegen = True,  # Whether or not to use experimental code generation support.
                        usecodegenweave = True,  # Whether or not to use C with experimental code generation support.
                        usecodegenstateupdate = True,  # Whether or not to use experimental code generation support on state updaters.
                        usecodegenthreshold = False,  # Whether or not to use experimental code generation support on thresholds.
                        usenewpropagate = True,  # Whether or not to use experimental new C propagation functions.
                        usecstdp = True,  # Whether or not to use experimental new C STDP.
                       )


np.random.seed(0)
data_path = './'
if test_mode:
    weight_path = data_path + 'weights/'
    num_examples = 10000 * 1
    use_testing_set = True
    do_plot_performance = False
    record_spikes = True
def run_sim(ffExcInputMult=None, ffInhInputMult=None):
    """Run the cond-based LIF neuron simulation.  Takes a few minutes to construct network and run


    Parameters
    ----------
    ffExcInputMult: scalar: FF input magnitude to E cells.  multiply ffInputV by this value and connect to E cells
    ffInhInputMult: scalar: FF input magnitude to I cells.

    Returns
    -------
    outDict - spike times, records of continuous values from simulation

    """

    # use helper to get input timecourses
    (ffInputV, condAddV) = create_input_vectors(
        doDebugPlot=False)  # multiplied by scalars below

    # setup initial state
    stT = time.time()
    brian.set_global_preferences(usecodegen=True)
    brian.set_global_preferences(useweave=True)
    brian.set_global_preferences(usecodegenweave=True)
    brian.clear(erase=True, all=True)
    brian.reinit_default_clock()
    clk = brian.Clock(dt=0.05 * ms)

    ################

    # create neurons, define connections
    neurNetwork = brian.NeuronGroup(nNet,
                                    model=eqs,
                                    threshold=vthresh,
                                    reset=vrest,
                                    refractory=absRefractoryMs * msecond,
                                    order=1,
                                    compile=True,
                                    freeze=False,
                                    clock=clk)

    # create neuron pools
    neurCE = neurNetwork.subgroup(nExc)
    neurCI = neurNetwork.subgroup(nInh)
    connCE = brian.Connection(neurCE, neurNetwork, 'ge')
    connCI = brian.Connection(neurCI, neurNetwork, 'gi')
    print('n cells: %d, nE,I %d,%d, %s, absRefractoryMs: %d' %
          (nNet, nExc, nInh, repr(clk), absRefractoryMs))

    # connect the network to itself
    connCE.connect_random(neurCE,
                          neurNetwork,
                          internalSparseness,
                          weight=connENetWeight)
    connCI.connect_random(neurCI,
                          neurNetwork,
                          internalSparseness,
                          weight=connINetWeight)

    # connect inputs that change spont rate
    assert (
        spontAddRate <= 0
    ), 'Spont add rate should be negative - convention: neg, excite inhibitory cells'
    spontAddNInpSyn = 100
    nTotalSpontNeurons = (spontAddNInpSyn * nInh * 0.02)
    neurSpont = brian.PoissonGroup(nTotalSpontNeurons,
                                   -1.0 * spontAddRate * Hz)
    connCSpont = brian.Connection(neurSpont, neurCI, 'ge')
    connCSpont.connect_random(
        p=spontAddNInpSyn * 1.0 / nTotalSpontNeurons,
        weight=connENetWeight,  # match internal excitatory strengths
        fixed=True)

    # connect the feedforward visual (poisson) inputs to excitatory cells (ff E)
    ffExcInputNInpSyn = 100
    nTotalFfNeurons = (ffExcInputNInpSyn * ffExcInputNTargs * 0.02
                       )  # one pop of input cells for both E and I FF
    _ffExcInputV = ffExcInputMult * np.abs(a_(ffInputV).copy())
    assert (np.all(
        _ffExcInputV >= 0)), 'Negative FF rates are rectified to zero'
    neurFfExcInput = brian.PoissonGroup(
        nTotalFfNeurons, lambda t: _ffExcInputV[int(t * 1000)] * Hz)
    connCFfExcInput = brian.Connection(neurFfExcInput, neurNetwork, 'ge')
    connCFfExcInput.connect_random(neurFfExcInput,
                                   neurCE[0:ffExcInputNTargs],
                                   ffExcInputNInpSyn * 1.0 / nTotalFfNeurons,
                                   weight=connENetWeight,
                                   fixed=True)

    # connect the feedforward visual (poisson) inputs to inhibitory cells (ff I)
    ffInhInputNInpSyn = 100
    _ffInhInputV = ffInhInputMult * np.abs(ffInputV.copy())
    assert (np.all(
        _ffInhInputV >= 0)), 'Negative FF rates are rectified to zero'
    neurFfInhInput = brian.PoissonGroup(
        nTotalFfNeurons, lambda t: _ffInhInputV[int(t * 1000)] * Hz)
    connCFfInhInput = brian.Connection(neurFfInhInput, neurNetwork, 'ge')
    connCFfInhInput.connect_random(
        neurFfInhInput,
        neurCI[0:ffInhInputNTargs],
        ffInhInputNInpSyn * 1.0 / nTotalFfNeurons,  # sparseness
        weight=connENetWeight,
        fixed=True)

    # connect added step (ChR2) conductance to excitatory cells
    condAddAmp = 4.0
    gAdd = brian.TimedArray(condAddAmp * condAddV, dt=1 * ms)
    print('Adding conductance for %d cells (can be slow): ' %
          len(condAddNeurNs),
          end=' ')
    for (iN, tN) in enumerate(condAddNeurNs):
        neurCE[tN].gAdd = gAdd
    print('done')

    # Initialize using some randomness so all neurons don't start in same state.
    # Alternative: initialize with constant values, give net extra 100-300ms to evolve from initial state.
    neurNetwork.v = (brian.randn(1) * 5.0 - 65) * mvolt
    neurNetwork.ge = brian.randn(nNet) * 1.5 + 4
    neurNetwork.gi = brian.randn(nNet) * 12 + 20

    # Record continuous variables and spikes
    monSTarg = brian.SpikeMonitor(neurNetwork)
    if contRecNs is not None:
        contRecClock = brian.Clock(dt=contRecStepMs * ms)
        monVTarg = brian.StateMonitor(neurNetwork,
                                      'v',
                                      record=contRecNs,
                                      clock=contRecClock)
        monGETarg = brian.StateMonitor(neurNetwork,
                                       'ge',
                                       record=contRecNs,
                                       clock=contRecClock)
        monGAddTarg = brian.StateMonitor(neurNetwork,
                                         'gAdd',
                                         record=contRecNs,
                                         clock=contRecClock)
        monGITarg = brian.StateMonitor(neurNetwork,
                                       'gi',
                                       record=contRecNs,
                                       clock=contRecClock)

    # construct brian.Network before running (so brian explicitly knows what to update during run)
    netL = [
        neurNetwork, connCE, connCI, monSTarg, neurFfExcInput, connCFfExcInput,
        neurFfInhInput, connCFfInhInput, neurSpont, connCSpont
    ]
    if contRecNs is not None:
        # noinspection PyUnboundLocalVariable
        netL.append([monVTarg, monGETarg, monGAddTarg,
                     monGITarg])  # cont monitors
    net = brian.Network(netL)
    print("Network construction time: %3.1f seconds" % (time.time() - stT))

    # run
    print("Simulation running...")
    sys.stdout.flush()
    start_time = time.time()
    net.run(simRunTimeS * second, report='text', report_period=30.0 * second)
    durationS = time.time() - start_time
    print("Simulation time: %3.1f seconds" % durationS)

    outNTC = collections.namedtuple(
        'outNTC',
        'vm ge gadd gi clockDtS clockStartS clockEndS spiketimes contRecNs')
    outNTC.__new__.__defaults__ = (None, ) * len(
        outNTC._fields)  # default to None
    outNT = outNTC(clockDtS=float(monSTarg.clock.dt),
                   clockStartS=float(monSTarg.clock.start),
                   clockEndS=float(monSTarg.clock.end),
                   spiketimes=a_(monSTarg.spiketimes.values(), dtype='O'),
                   contRecNs=contRecNs)
    if contRecNs is not None:
        outNT = outNT._replace(vm=monVTarg.values,
                               ge=monGETarg.values,
                               gadd=monGAddTarg.values,
                               gi=monGITarg.values)
    return outNT
testing = get_labeled_data(MNIST_data_path + 'testing', bTrain = False)
end = time.time()
print 'time needed to load test set:', end - start


#------------------------------------------------------------------------------ 
# set parameters and equations
#------------------------------------------------------------------------------
test_mode = True

b.set_global_preferences( 
                        defaultclock = b.Clock(dt=0.5*b.ms), # The default clock to use if none is provided or defined in any enclosing scope.
                        useweave = True, # Defines whether or not functions should use inlined compiled C code where defined.
                        gcc_options = ['-ffast-math -march=native'],  # Defines the compiler switches passed to the gcc compiler. 
                        #For gcc versions 4.2+ we recommend using -march=native. By default, the -ffast-math optimizations are turned on 
                        usecodegen = True,  # Whether or not to use experimental code generation support.
                        usecodegenweave = True,  # Whether or not to use C with experimental code generation support.
                        usecodegenstateupdate = True,  # Whether or not to use experimental code generation support on state updaters.
                        usecodegenthreshold = False,  # Whether or not to use experimental code generation support on thresholds.
                        usenewpropagate = True,  # Whether or not to use experimental new C propagation functions.
                        usecstdp = True,  # Whether or not to use experimental new C STDP.
                       ) 


np.random.seed(0)
data_path = './'
if test_mode:
    weight_path = data_path + 'weights/'
    num_examples = 10000 * 1
    use_testing_set = True
    do_plot_performance = False
    record_spikes = True
Esempio n. 10
0
import brian_no_units  #import it to deactivate unit checking --> This should NOT be done for testing/debugging 
import brian as b
from brian import *
b.set_global_preferences( 
                        defaultclock = b.Clock(dt=0.25*b.ms), # The default clock to use if none is provided or defined in any enclosing scope.
                        useweave = True, # Defines whether or not functions should use inlined compiled C code where defined.
                        gcc_options = ['-ffast-math -march=native'],  # Defines the compiler switches passed to the gcc compiler. 
                        #For gcc versions 4.2+ we recommend using -march=native. By default, the -ffast-math optimisations are turned on 
                        #- if you need IEEE guaranteed results, turn this switch off.
                        useweave_linear_diffeq = True,  # Whether to use weave C++ acceleration for the solution of linear differential 
                        #equations. Note that on some platforms, typically older ones, this is faster and on some platforms, 
                        #typically new ones, this is actually slower.
                        usecodegen = True,  # Whether or not to use experimental code generation support.
                        usecodegenweave = True,  # Whether or not to use C with experimental code generation support.
                        usecodegenstateupdate = True,  # Whether or not to use experimental code generation support on state updaters.
                        usecodegenreset = False,  # Whether or not to use experimental code generation support on resets. 
                        #Typically slower due to weave overheads, so usually leave this off.
                        usecodegenthreshold = True,  # Whether or not to use experimental code generation support on thresholds.
                        usenewpropagate = True,  # Whether or not to use experimental new C propagation functions.
                        usecstdp = True,  # Whether or not to use experimental new C STDP.
                        openmp = False,  # Whether or not to use OpenMP pragmas in generated C code. 
                        #If supported on your compiler (gcc 4.2+) it will use multiple CPUs and can run substantially faster.
                        magic_useframes = True,  # Defines whether or not the magic functions should search for objects 
                        #defined only in the calling frame or if they should find all objects defined in any frame. 
                        #This should be set to False if you are using Brian from an interactive shell like IDLE or IPython 
                        #where each command has its own frame, otherwise set it to True.
                       ) 
  
# import brian.experimental.cuda.gpucodegen as gpu
np.random.seed(0)
Esempio n. 11
0
experiment_path = './results/'

if len(sys.argv) == 2:
    experiment_number = int(sys.argv[1])
    print 'EXPERIMENT', experiment_number

b.set_global_preferences(
    defaultclock=b.Clock(
        dt=0.1 * b.ms),  # The default clock to use if none is provided.
    useweave=
    True,  # 301 Defines whether or not functions should use inlined compiled C code where defined.
    gcc_options=[
        '-march=native'
    ],  # Defines the compiler switches passed to the gcc compiler.
    usecodegen=
    True,  # Whether or not to use experimental code generation support.
    usecodegenweave=
    True,  # Whether or not to use C with experimental code generation support.
    usecodegenstateupdate=
    True,  # Whether or not to use experimental code generation support on state updaters.
    usecodegenthreshold=
    False,  # Whether or not to use experimental code generation support on thresholds.
    usenewpropagate=
    True,  # Whether or not to use experimental new C propagation functions.
    usecstdp=True,  # Whether or not to use experimental new C STDP.
)

# SYSTEM PARAMETERS
sensory_neurons = 784
spiking_neurons = 400
inhibitory_neurons = 400
b.ion()

print u"\U0001F637"

b.set_global_preferences( 
                        defaultclock = b.Clock(dt=timestep*b.second), # The default clock to use if none is provided or defined in any enclosing scope.
                        useweave=True, # Defines whether or not functions should use inlined compiled C code where defined.
                        gcc_options = ['-ffast-math -march=native'],  # Defines the compiler switches passed to the gcc compiler. 
                        #For gcc versions 4.2+ we recommend using -march=native. By default, the -ffast-math optimisations are turned on 
                        #- if you need IEEE guaranteed results, turn this switch off.
                        useweave_linear_diffeq = False,  # Whether to use weave C++ acceleration for the solution of linear differential 
                        #equations. Note that on some platforms, typically older ones, this is faster and on some platforms, 
                        #typically new ones, this is actually slower.
                        usecodegen = True,  # Whether or not to use experimental code generation support.
                        usecodegenweave = True,  # Whether or not to use C with experimental code generation support.
                        usecodegenstateupdate = True,  # Whether or not to use experimental code generation support on state updaters.
                        usecodegenreset = True,  # Whether or not to use experimental code generation support on resets. 
                        #Typically slower due to weave overheads, so usually leave this off.
                        usecodegenthreshold = True,  # Whether or not to use experimental code generation support on thresholds.
                        usenewpropagate = True,  # Whether or not to use experimental new C propagation functions.
                        usecstdp = True,  # Whether or not to use experimental new C STDP.
                        openmp = False,  # Whether or not to use OpenMP pragmas in generated C code. 
                        #If supported on your compiler (gcc 4.2+) it will use multiple CPUs and can run substantially faster.
                        magic_useframes = True,  # Defines whether or not the magic functions should search for objects 
                        #defined only in the calling frame or if they should find all objects defined in any frame. 
                        #This should be set to False if you are using Brian from an interactive shell like IDLE or IPython 
                        #where each command has its own frame, otherwise set it to True.
                       ) 



neuron_eqs = '''
Esempio n. 13
0
testing = get_labeled_data(MNIST_data_path + 'testing', bTrain = False)
end = time.time()
print 'time needed to load test set:', end - start


#------------------------------------------------------------------------------ 
# set parameters and equations
#------------------------------------------------------------------------------
test_mode = False

b.set_global_preferences(
                        defaultclock = b.Clock(dt=0.5*b.ms),
                        useweave = True,
                        gcc_options = ['-ffast-math -march=native'],
                        usecodegen = True,
                        usecodegenweave = True,
                        usecodegenstateupdate = True,
                        usecodegenthreshold = False,
                        usenewpropagate = True,
                        usecstdp = True,
                    )

np.random.seed(0)
data_path = './'
if test_mode:
    weight_path = data_path + 'weights/'
    num_examples = 10000 * 1
    use_testing_set = True
    do_plot_performance = False
    record_spikes = True
    ee_STDP_on = False
"""
NMDA synapses
"""
from brian import NeuronGroup, StateMonitor, set_global_preferences, run, Clock
from brian.stdunits import ms
import time
from brian.experimental.synapses import *

from brian import log_level_debug
log_level_debug()

set_global_preferences(useweave=True,usecodegen=True,usecodegenweave=True,usenewpropagate=True,usecstdp=True)

from matplotlib.pyplot import plot, show, subplot

params = {}
params["t_Nr"] = 2*ms
params["t_Nf"] = 80*ms
params["t_AMPA"] = 5*ms


simclock = Clock(dt=0.01*ms)

input=NeuronGroup(2,model='dv/dt=1/(10*ms):1', threshold=1, reset=0,clock=simclock)
neurons = NeuronGroup(1, model="""dv/dt=(NMDAo+AMPAo-v)/(10*ms) : 1
                                  NMDAo : 1
                                  AMPAo : 1""", freeze = True,clock=simclock)

ampadyn = '''
        dAMPAoS/dt = -AMPAoS/t_AMPA            : 1
        AMPAi = AMPAoS