Beispiel #1
0
def setup_2_layers_4_units_ff_net():
    configure_scheduling()
    pynnn.setup()
    Tns.p1 = pynnn.Population(4, pynnn.IF_curr_alpha,
                          structure=pynnn.space.Grid2D())
    Tns.p2 = pynnn.Population(4, pynnn.IF_curr_alpha,
                          structure=pynnn.space.Grid2D())
    Tns.prj1_2 = pynnn.Projection(
        Tns.p1, Tns.p2, pynnn.AllToAllConnector(allow_self_connections=False),
        target='excitatory')
    Tns.prj1_2.set("weight", 1)
    Tns.max_weight = 34
    Tns.rore1_update_p = 10
    Tns.rore1_win_width = 200
    Tns.rore2_update_p = 10
    Tns.rore2_win_width = 200
    Tns.rore1 = RectilinearOutputRateEncoder(Tns.p1, 2, 2,
                                             Tns.rore1_update_p,
                                             Tns.rore1_win_width)
    Tns.rore2 = RectilinearOutputRateEncoder(Tns.p2, 2, 2,
                                             Tns.rore2_update_p,
                                             Tns.rore2_win_width)
    common.pynn_utils.POP_ADAPT_DICT[(Tns.p1,
        common.pynn_utils.RectilinearOutputRateEncoder)] = Tns.rore1
    common.pynn_utils.POP_ADAPT_DICT[(Tns.p2,
        common.pynn_utils.RectilinearOutputRateEncoder)] = Tns.rore2
    enable_recording(Tns.p1, Tns.p2)
    schedule_output_rate_calculation(Tns.p1)
    schedule_output_rate_calculation(Tns.p2)
Beispiel #2
0
def setup_2_layers_4_units_ff_net():
    configure_scheduling()
    pynnn.setup()
    Tns.p1 = pynnn.Population(4,
                              pynnn.IF_curr_alpha,
                              structure=pynnn.space.Grid2D())
    Tns.p2 = pynnn.Population(4,
                              pynnn.IF_curr_alpha,
                              structure=pynnn.space.Grid2D())
    Tns.prj1_2 = pynnn.Projection(
        Tns.p1,
        Tns.p2,
        pynnn.AllToAllConnector(allow_self_connections=False),
        target='excitatory')
    Tns.prj1_2.set("weight", 1)
    Tns.max_weight = 34
    Tns.rore1_update_p = 10
    Tns.rore1_win_width = 200
    Tns.rore2_update_p = 10
    Tns.rore2_win_width = 200
    Tns.rore1 = RectilinearOutputRateEncoder(Tns.p1, 2, 2, Tns.rore1_update_p,
                                             Tns.rore1_win_width)
    Tns.rore2 = RectilinearOutputRateEncoder(Tns.p2, 2, 2, Tns.rore2_update_p,
                                             Tns.rore2_win_width)
    common.pynn_utils.POP_ADAPT_DICT[(
        Tns.p1, common.pynn_utils.RectilinearOutputRateEncoder)] = Tns.rore1
    common.pynn_utils.POP_ADAPT_DICT[(
        Tns.p2, common.pynn_utils.RectilinearOutputRateEncoder)] = Tns.rore2
    enable_recording(Tns.p1, Tns.p2)
    schedule_output_rate_calculation(Tns.p1)
    schedule_output_rate_calculation(Tns.p2)
Beispiel #3
0
def run_sim(ncell):

    print "Cells: ", ncell

    setup0 = time.time()

    sim.setup(timestep=0.1)

    hh_cell_type = sim.HH_cond_exp()

    hh = sim.Population(ncell, hh_cell_type)

    pulse = sim.DCSource(amplitude=0.5, start=20.0, stop=80.0)
    pulse.inject_into(hh)

    hh.record('v')

    setup1 = time.time()

    t0 = time.time()

    sim.run(100.0)

    v = hh.get_data()

    sim.end()

    t1 = time.time()

    setup_total = setup1 - setup0
    run_total = t1 - t0
    print "Setup: ", setup_total
    print "Run: ", run_total
    print "Total sim time: ", setup_total + run_total
    return run_total
Beispiel #4
0
def configure_scheduling():
    global SIMULATION_END_T
    sim.initialize()
    pynnn.setup()
    SIMULATION_END_T = 0
    RATE_ENC_RESPAWN_DICT.clear()
    POP_ADAPT_DICT.clear()
Beispiel #5
0
def configure_scheduling():
    global SIMULATION_END_T
    sim.initialize()
    pynnn.setup()
    SIMULATION_END_T = 0
    RATE_ENC_RESPAWN_DICT.clear()
    POP_ADAPT_DICT.clear()
Beispiel #6
0
def setup_pynn_populations_with_full_connectivity():
    pynnn.setup()
    Tns.p1 = pynnn.Population(4, pynnn.IF_curr_alpha, structure=pynnn.space.Grid2D())
    Tns.p2 = pynnn.Population(4, pynnn.IF_curr_alpha, structure=pynnn.space.Grid2D())
    Tns.prj1_2 = pynnn.Projection(
        Tns.p1, Tns.p2, pynnn.AllToAllConnector(allow_self_connections=False), target="excitatory"
    )
Beispiel #7
0
 def make_network(self, param_dict=default_params):
     """
     Construct the network according to the parameters specified.
     """
     pynn.setup()
     self.exc = pynn.Population(param_dict['num_e'], 
                                pynn.SpikeSourcePoisson, 
                                cellparams={'rate':param_dict['re']})
     self.inh = pynn.Population(param_dict['num_i'], 
                                pynn.SpikeSourcePoisson, 
                                cellparams={'rate':param_dict['ri']})
     self.target = pynn.Population(param_dict['num_t'], 
                                   pynn.IF_cond_exp)
     self.target.record(to_file=False)
     
     connector_et = pynn.FixedProbabilityConnector(
                         p_connect=param_dict["p_conn_et"],
                         weights=param_dict["we"])
     connector_ei = pynn.FixedProbabilityConnector(
                         p_connect=param_dict["p_conn_it"],
                         weights=param_dict["wi"])
     self.prj_et = pynn.Projection(self.exc, self.target, 
               method=connector_et)
     self.prj_it = pynn.Projection(self.inh, self.target, 
               method=connector_ei, target='inhibitory')
Beispiel #8
0
def setup_pynn_populations():
    pynnn.setup()
    Tns.p1 = pynnn.Population(64, pynnn.IF_curr_alpha, structure=pynnn.space.Grid2D())
    Tns.p2 = pynnn.Population(64, pynnn.IF_curr_alpha, structure=pynnn.space.Grid2D())
    Tns.prj1_2 = pynnn.Projection(
        Tns.p1, Tns.p2, pynnn.AllToAllConnector(allow_self_connections=False), target="excitatory"
    )
    # Weights in nA as IF_curr_alpha uses current-based synapses
    Tns.prj1_2.set("weight", 1)
    Tns.max_weight = 33
Beispiel #9
0
def setup_pynn_populations_with_1_to_1_connectivity():
    pynnn.setup()
    Tns.p1 = pynnn.Population(64,
                              pynnn.IF_curr_alpha,
                              structure=pynnn.space.Grid2D())
    Tns.p2 = pynnn.Population(64,
                              pynnn.IF_curr_alpha,
                              structure=pynnn.space.Grid2D())
    Tns.prj1_2 = pynnn.Projection(Tns.p1,
                                  Tns.p2,
                                  pynnn.OneToOneConnector(),
                                  target='excitatory')
Beispiel #10
0
 def setUp(self):
     sim.setup()
     sim.Population.nPop = 0
     sim.Projection.nProj = 0
     self.target33 = sim.Population((3, 3), sim.IF_curr_alpha)
     self.target6 = sim.Population((6, ), sim.IF_curr_alpha)
     self.target1 = sim.Population((1, ), sim.IF_cond_exp)
     self.source5 = sim.Population((5, ), sim.SpikeSourcePoisson)
     self.source22 = sim.Population((2, 2), sim.SpikeSourcePoisson)
     self.source33 = sim.Population((3, 3), sim.SpikeSourcePoisson)
     self.expoisson33 = sim.Population((3, 3), sim.SpikeSourcePoisson,
                                       {'rate': 100})
Beispiel #11
0
def setup_pynn_populations_with_full_connectivity():
    pynnn.setup()
    Tns.p1 = pynnn.Population(4,
                              pynnn.IF_curr_alpha,
                              structure=pynnn.space.Grid2D())
    Tns.p2 = pynnn.Population(4,
                              pynnn.IF_curr_alpha,
                              structure=pynnn.space.Grid2D())
    Tns.prj1_2 = pynnn.Projection(
        Tns.p1,
        Tns.p2,
        pynnn.AllToAllConnector(allow_self_connections=False),
        target='excitatory')
Beispiel #12
0
def setup_pynn_populations():
    pynnn.setup()
    Tns.p1 = pynnn.Population(64,
                              pynnn.IF_curr_alpha,
                              structure=pynnn.space.Grid2D())
    Tns.p2 = pynnn.Population(64,
                              pynnn.IF_curr_alpha,
                              structure=pynnn.space.Grid2D())
    Tns.prj1_2 = pynnn.Projection(
        Tns.p1,
        Tns.p2,
        pynnn.AllToAllConnector(allow_self_connections=False),
        target='excitatory')
    # Weights in nA as IF_curr_alpha uses current-based synapses
    Tns.prj1_2.set("weight", 1)
    Tns.max_weight = 33
Beispiel #13
0
def generate_data(label):
    spikesTrain = []
    organisedData = {}
    for i in range(input_class):
        for j in range(input_len):
            neuid = (i, j)
            organisedData[neuid] = []
    for i in range(input_len):
        neuid = (label, i)
        organisedData[neuid].append(i * v_co)


#        if neuid not in organisedData:
#            organisedData[neuid]=[i*v_co]
#        else:
#            organisedData[neuid].append(i*v_co)
    for i in range(input_class):
        for j in range(input_len):
            neuid = (i, j)
            organisedData[neuid].sort()
            spikesTrain.append(organisedData[neuid])
    runTime = int(max(max(spikesTrain)))
    sim.setup(timestep=1)

    noise = sim.Population(input_size, sim.SpikeSourcePoisson(), label='noise')

    noise.record(['spikes'])  #noise

    sim.run(runTime)
    neonoise = noise.get_data(["spikes"])
    spikesnoise = neonoise.segments[0].spiketrains  #noise
    sim.end()
    for i in range(input_size):
        for noisespike in spikesnoise[i]:
            spikesTrain[i].append(noisespike)
            spikesTrain[i].sort()
    return spikesTrain
Beispiel #14
0
def setup_pynn_populations_with_1_to_1_connectivity():
    pynnn.setup()
    Tns.p1 = pynnn.Population(64, pynnn.IF_curr_alpha, structure=pynnn.space.Grid2D())
    Tns.p2 = pynnn.Population(64, pynnn.IF_curr_alpha, structure=pynnn.space.Grid2D())
    Tns.prj1_2 = pynnn.Projection(Tns.p1, Tns.p2, pynnn.OneToOneConnector(), target="excitatory")
Beispiel #15
0
def train(label, untrained_weights=None):
    organisedStim = {}
    labelSpikes = []
    spikeTimes = generate_data(label)

    for i in range(output_size):
        labelSpikes.append([])
    labelSpikes[label] = [int(max(max(spikeTimes))) + 1]

    if untrained_weights == None:
        untrained_weights = RandomDistribution('uniform',
                                               low=wMin,
                                               high=wMaxInit).next(input_size *
                                                                   output_size)
        #untrained_weights = RandomDistribution('normal_clipped', mu=0.1, sigma=0.05, low=wMin, high=wMaxInit).next(input_size*output_size)
        untrained_weights = np.around(untrained_weights, 3)
        #saveWeights(untrained_weights, 'untrained_weightssupmodel1traj')
        print("init!")

    print "length untrained_weights :", len(untrained_weights)

    if len(untrained_weights) > input_size:
        training_weights = [[0 for j in range(output_size)]
                            for i in range(input_size)
                            ]  #np array? size 1024x25
        k = 0
        #for i in untrained_weights:
        #    training_weights[i[0]][i[1]]=i[2]
        for i in range(input_size):
            for j in range(output_size):
                training_weights[i][j] = untrained_weights[k]
                k += 1
    else:
        training_weights = untrained_weights

    connections = []
    for n_pre in range(input_size):  # len(untrained_weights) = input_size
        for n_post in range(
                output_size
        ):  # len(untrained_weight[0]) = output_size; 0 or any n_pre
            connections.append((n_pre, n_post, training_weights[n_pre][n_post],
                                __delay__))  #index
    runTime = int(max(max(spikeTimes))) + 100
    #####################
    sim.setup(timestep=1)
    #def populations
    layer1 = sim.Population(input_size,
                            sim.SpikeSourceArray, {'spike_times': spikeTimes},
                            label='inputspikes')
    layer2 = sim.Population(output_size,
                            sim.IF_curr_exp,
                            cellparams=cell_params_lif,
                            label='outputspikes')
    supsignal = sim.Population(output_size,
                               sim.SpikeSourceArray,
                               {'spike_times': labelSpikes},
                               label='supersignal')

    #def learning rule
    stdp = sim.STDPMechanism(
        #weight=untrained_weights,
        #weight=0.02,  # this is the initial value of the weight
        #delay="0.2 + 0.01*d",
        timing_dependence=sim.SpikePairRule(tau_plus=tauPlus,
                                            tau_minus=tauMinus,
                                            A_plus=aPlus,
                                            A_minus=aMinus),
        #weight_dependence=sim.MultiplicativeWeightDependence(w_min=wMin, w_max=wMax),
        weight_dependence=sim.AdditiveWeightDependence(w_min=wMin, w_max=wMax),
        dendritic_delay_fraction=0)
    #def projections

    stdp_proj = sim.Projection(layer1,
                               layer2,
                               sim.FromListConnector(connections),
                               synapse_type=stdp)
    inhibitory_connections = sim.Projection(
        layer2,
        layer2,
        sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=sim.StaticSynapse(weight=inhibWeight, delay=__delay__),
        receptor_type='inhibitory')
    stim_proj = sim.Projection(supsignal,
                               layer2,
                               sim.OneToOneConnector(),
                               synapse_type=sim.StaticSynapse(
                                   weight=stimWeight, delay=__delay__))

    layer1.record(['spikes'])

    layer2.record(['v', 'spikes'])
    supsignal.record(['spikes'])
    sim.run(runTime)

    print("Weights:{}".format(stdp_proj.get('weight', 'list')))

    weight_list = [
        stdp_proj.get('weight', 'list'),
        stdp_proj.get('weight', format='list', with_address=False)
    ]
    neo = layer2.get_data(["spikes", "v"])
    spikes = neo.segments[0].spiketrains
    v = neo.segments[0].filter(name='v')[0]
    neostim = supsignal.get_data(["spikes"])
    print(label)
    spikestim = neostim.segments[0].spiketrains
    neoinput = layer1.get_data(["spikes"])
    spikesinput = neoinput.segments[0].spiketrains

    plt.close('all')
    pplt.Figure(pplt.Panel(v,
                           ylabel="Membrane potential (mV)",
                           xticks=True,
                           yticks=True,
                           xlim=(0, runTime)),
                pplt.Panel(spikesinput,
                           xticks=True,
                           yticks=True,
                           markersize=2,
                           xlim=(0, runTime)),
                pplt.Panel(spikestim,
                           xticks=True,
                           yticks=True,
                           markersize=2,
                           xlim=(0, runTime)),
                pplt.Panel(spikes,
                           xticks=True,
                           xlabel="Time (ms)",
                           yticks=True,
                           markersize=2,
                           xlim=(0, runTime)),
                title="Training" + str(label),
                annotations="Training" +
                str(label)).save('plot/' + str(trylabel) + str(label) +
                                 '_training.png')
    #plt.hist(weight_list[1], bins=100)
    #plt.show()
    plt.close('all')
    print(wMax)
    '''
    plt.hist([weight_list[1][0:input_size], weight_list[1][input_size:input_size*2], weight_list[1][input_size*2:]], bins=20, label=['neuron 0', 'neuron 1', 'neuron 2'], range=(0, wMax))
    plt.title('weight distribution')
    plt.xlabel('Weight value')
    plt.ylabel('Weight count')
    '''
    #plt.show()
    #plt.show()

    sim.end()
    for i in weight_list[0]:
        #training_weights[int(i[0])][int(i[1])]=float(i[2])
        weight_list[1][int(i[0]) * output_size + int(i[1])] = i[2]
    return weight_list[1]
Beispiel #16
0
def test(spikeTimes, trained_weights, label):

    #spikeTimes = extractSpikes(sample)
    runTime = int(max(max(spikeTimes))) + 100

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

    sim.setup(timestep=1)

    pre_pop = sim.Population(input_size,
                             sim.SpikeSourceArray, {'spike_times': spikeTimes},
                             label="pre_pop")
    post_pop = sim.Population(output_size,
                              sim.IF_curr_exp,
                              cell_params_lif,
                              label="post_pop")
    '''
    if len(untrained_weights)>input_size:
        training_weights = [[0 for j in range(output_size)] for i in range(input_size)] #np array? size 1024x25
        k=0
        for i in untrained_weights:
            training_weights[i[0]][i[1]]=i[2]
    '''
    if len(trained_weights) > input_size:
        weigths = [[0 for j in range(output_size)]
                   for i in range(input_size)]  #np array? size 1024x25
        k = 0
        for i in range(input_size):
            for j in range(output_size):
                weigths[i][j] = trained_weights[k]
                k += 1
    else:
        weigths = trained_weights

    connections = []

    #k = 0
    for n_pre in range(input_size):  # len(untrained_weights) = input_size
        for n_post in range(
                output_size
        ):  # len(untrained_weight[0]) = output_size; 0 or any n_pre
            #connections.append((n_pre, n_post, weigths[n_pre][n_post]*(wMax), __delay__))
            connections.append((n_pre, n_post, weigths[n_pre][n_post] *
                                (wMax) / max(trained_weights), __delay__))  #
            #k += 1

    prepost_proj = sim.Projection(
        pre_pop,
        post_pop,
        sim.FromListConnector(connections),
        synapse_type=sim.StaticSynapse(),
        receptor_type='excitatory')  # no more learning !!
    #inhib_proj = sim.Projection(post_pop, post_pop, sim.AllToAllConnector(), synapse_type=sim.StaticSynapse(weight=inhibWeight, delay=__delay__), receptor_type='inhibitory')
    # no more lateral inhib

    post_pop.record(['v', 'spikes'])
    sim.run(runTime)

    neo = post_pop.get_data(['v', 'spikes'])
    spikes = neo.segments[0].spiketrains
    v = neo.segments[0].filter(name='v')[0]
    f1 = pplt.Figure(
        # plot voltage
        pplt.Panel(v,
                   ylabel="Membrane potential (mV)",
                   xticks=True,
                   yticks=True,
                   xlim=(0, runTime + 100)),
        # raster plot
        pplt.Panel(spikes,
                   xlabel="Time (ms)",
                   xticks=True,
                   yticks=True,
                   markersize=2,
                   xlim=(0, runTime + 100)),
        title='Test with label ' + str(label),
        annotations='Test with label ' + str(label))
    f1.save('plot/' + str(trylabel) + str(label) + '_test.png')
    f1.fig.texts = []
    print("Weights:{}".format(prepost_proj.get('weight', 'list')))

    weight_list = [
        prepost_proj.get('weight', 'list'),
        prepost_proj.get('weight', format='list', with_address=False)
    ]
    #predict_label=
    sim.end()
    return spikes
import pyNN.brian as sim
import matplotlib.pyplot as plt
from pyNN.utility.plotting import Figure, Panel

sim.setup(timestep=0.1, min_delay=2.0)
ifcell = sim.create(sim.IF_cond_exp, {
    'i_offset': 0.11,
    'tau_refrac': 3.0,
    'v_thresh': -51.0
},
                    n=10)
'''
pulse = sim.DCSource(amplitude=0.5, start=20.0, stop=80.0)
pulse.inject_into(ifcell[3:7])

ifcell.record('v')
sim.run(100.0)

data = ifcell.get_data()
sim.end()
'''
'''
vm = data.filter(name="v")[0]

Figure(
    Panel(vm, ylabel="Membrane potential (mV)")
).show
'''
'''
sine = sim.ACSource(start=50.0, stop=450.0, amplitude=1.0, offset=1.0,
                frequency=10.0, phase=180.0)
Beispiel #18
0
import pyNN.brian as sim  # can of course replace `neuron` with `nest`, `brian`, etc.
import matplotlib.pyplot as plt
import numpy as np

sim.setup(timestep=0.01)
p_in = sim.Population(10, sim.SpikeSourcePoisson(rate=10.0), label="input")
p_out = sim.Population(10, sim.EIF_cond_exp_isfa_ista(), label="AdExp neurons")

syn = sim.StaticSynapse(weight=0.05)
random = sim.FixedProbabilityConnector(p_connect=0.5)
connections = sim.Projection(p_in,
                             p_out,
                             random,
                             syn,
                             receptor_type='excitatory')

p_in.record('spikes')
p_out.record('spikes')  # record spikes from all neurons
p_out[0:2].record(['v', 'w', 'gsyn_exc'
                   ])  # record other variables from first two neurons

for i in range(2):
    sim.run(500.0)
    spikes_in = p_in.get_data()
    data_out = p_out.get_data()
    sim.reset()
    connections.set(weight=0.05)

sim.end()
print 'finish simulation'
Exc_in = 32  # number of excitatory inputs
Inh_in = 32  # number of inhibitatory inputs
# No_inp = {'exc': 32, 'inh': 32}

run_time = 500  # define the simulation time

# ==========generate OR read in the input spikes data=====================
noSpikes = 20  # number of spikes per chanel per simulation run
stimSpikes = RandomDistribution(
    'uniform', low=0, high=run_time, rng=NumpyRNG(seed=72386)
).next(
    [Exc_in + Inh_in, noSpikes]
)  # generate a time uniform distributed signal with Exc_in + Inh_in chanels and noSpikes for each chanel
# todo: 64 chanel represents different data

sim.setup()  # start buiding up the network topology

# ==========create the input signal neuron population==================
# form the Exc_in chanels excitatory inputs as a assembly Inhinp
for i in range(Exc_in):
    if i == 0:
        Excinp = sim.Population(
            1, sim.SpikeSourceArray(spike_times=stimSpikes[i, :]))
    else:
        spike_source = sim.Population(
            1, sim.SpikeSourceArray(spike_times=stimSpikes[i, :]))
        Excinp = Excinp + spike_source

# form the Inh_in chanels excitatory inputs as a assembly Inhinp
for i in range(Inh_in):
    if i == 0:
Beispiel #20
0
 def setUp(self):
     sim.setup()
     self.syn = sim.StaticSynapse(weight=0.123, delay=0.5)
Beispiel #21
0
# You should have received a copy of the GNU General Public License
# along with PyCogMo.  If not, see <http://www.gnu.org/licenses/>.

""" Utilities and algorithms to integrate PyNN and SimPy
"""

import pyNN.brian as pynnn
import SimPy.Simulation as sim
from common.pynn_utils import get_input_layer, get_rate_encoder, \
    InputSample, RectilinearInputLayer, InvalidMatrixShapeError, \
    POP_ADAPT_DICT
from common.utils import LOGGER, optimal_rounding

SIMULATION_END_T = 0

pynnn.setup()
PYNN_TIME_STEP = pynnn.get_time_step()
PYNN_TIME_ROUNDING = optimal_rounding(PYNN_TIME_STEP)

RATE_ENC_RESPAWN_DICT = dict()


class DummyProcess(sim.Process):
    def ACTIONS(self):
        yield sim.hold, self, 0


def get_current_time():
    return sim.now()

Beispiel #22
0
 def setUp(self):
     sim.setup()
     self.syn = sim.StaticSynapse(weight=0.123, delay=0.5)
Beispiel #23
0
def main():
    ## Uninteresting setup, start up the visu process,...
    logfile = make_logfile_name()
    ensure_dir(logfile)
    f_h = logging.FileHandler(logfile)
    f_h.setLevel(SUBDEBUG)
    d_h = logging.StreamHandler()
    d_h.setLevel(INFO)
    utils.configure_loggers(debug_handler=d_h, file_handler=f_h)
    parent_conn, child_conn = multiprocessing.Pipe()
    p = multiprocessing.Process(
        target=visualisation.visualisation_process_f,
        name="display_process", args=(child_conn, LOGGER))
    p.start()

    pynnn.setup(timestep=SIMU_TIMESTEP)
    init_logging("logfile", debug=True)
    LOGGER.info("Simulation started with command: %s", sys.argv)

    ## Network setup
    # First population
    p1 = pynnn.Population(100, pynnn.IF_curr_alpha,
                          structure=pynnn.space.Grid2D())
    p1.set({'tau_m':20, 'v_rest':-65})
    # Second population
    p2 = pynnn.Population(20, pynnn.IF_curr_alpha,
                          cellparams={'tau_m': 15.0, 'cm': 0.9})
    # Projection 1 -> 2
    prj1_2 = pynnn.Projection(
        p1, p2, pynnn.AllToAllConnector(allow_self_connections=False),
        target='excitatory')
    # I may need to make own PyNN Connector class. Otherwise, this is
    # neat:  exponentially decaying probability of connections depends
    # on distance. Distance is only calculated using x and y, which
    # are on a toroidal topo with boundaries at 0 and 500.
    connector = pynnn.DistanceDependentProbabilityConnector(
        "exp(-abs(d))",
        space=pynnn.Space(
            axes='xy', periodic_boundaries=((0,500), (0,500), None)))
    # Alternately, the powerful connection set algebra (python CSA
    # module) can be used.
    weight_distr = pynnn.RandomDistribution(distribution='gamma',
                                            parameters=[1,0.1])
    prj1_2.randomizeWeights(weight_distr)

    # This one is in NEST but not in Brian:
    # source = pynnn.NoisyCurrentSource(
    #     mean=100, stdev=50, dt=SIMU_TIMESTEP, 
    #     start=10.0, stop=SIMU_DURATION, rng=pynnn.NativeRNG(seed=100)) 
    source = pynnn.DCSource(
        start=10.0, stop=SIMU_DURATION, amplitude=100) 
    source.inject_into(list(p1.sample(50).all()))

    p1.record(to_file=False)
    p2.record(to_file=False)

    ## Build and send the visualizable network structure
    adapter = pynn_to_visu.PynnToVisuAdapter(LOGGER)
    adapter.add_pynn_population(p1)
    adapter.add_pynn_population(p2)
    adapter.add_pynn_projection(p1, p2, prj1_2.connection_manager)
    adapter.commit_structure()
    
    parent_conn.send(adapter.output_struct)
    
    # Number of chunks to run the simulation:
    n_chunks = SIMU_DURATION // SIMU_TO_VISU_MESSAGE_PERIOD
    last_chunk_duration = SIMU_DURATION % SIMU_TO_VISU_MESSAGE_PERIOD
    # Run the simulator
    for visu_i in xrange(n_chunks):
        pynnn.run(SIMU_TO_VISU_MESSAGE_PERIOD)
        parent_conn.send(adapter.make_activity_update_message())
        LOGGER.debug("real current p1 spike counts: %s",
                     p1.get_spike_counts().values())
    if last_chunk_duration > 0:
        pynnn.run(last_chunk_duration)
        parent_conn.send(adapter.make_activity_update_message())
    # Cleanup
    pynnn.end()
    # Wait for the visualisation process to terminate
    p.join(VISU_PROCESS_JOIN_TIMEOUT)
Beispiel #24
0
# You should have received a copy of the GNU General Public License
# along with PyCogMo.  If not, see <http://www.gnu.org/licenses/>.

import itertools
import logging
from logging import NullHandler
from mock import Mock, patch
from nose import with_setup
from nose.tools import eq_, raises, timed
from ui.graphical.pynn_to_visu import *
import pyNN.brian as pynnn

DUMMY_LOGGER = logging.getLogger("testLogger")
DUMMY_LOGGER.addHandler(NullHandler())
A = None
pynnn.setup()


def setup_adapter():
    global A
    A = PynnToVisuAdapter(DUMMY_LOGGER)


# holder class ("namespace") for the test variables
class Tns(object):
    pass


def setup_and_fill_adapter():
    setup_adapter()
    Tns.pop_size = 27
import pyNN.brian as sim
sim.setup()

cell = sim.Population(1, sim.HH_cond_exp())
cell.record('v')
sim.run(100)
data = cell.get_data()
sim.end()
Beispiel #26
0
def main():
    ## Uninteresting setup, start up the visu process,...
    logfile = make_logfile_name()
    ensure_dir(logfile)
    f_h = logging.FileHandler(logfile)
    f_h.setLevel(SUBDEBUG)
    d_h = logging.StreamHandler()
    d_h.setLevel(INFO)
    utils.configure_loggers(debug_handler=d_h, file_handler=f_h)
    parent_conn, child_conn = multiprocessing.Pipe()
    p = multiprocessing.Process(target=visualisation.visualisation_process_f,
                                name="display_process",
                                args=(child_conn, LOGGER))
    p.start()

    pynnn.setup(timestep=SIMU_TIMESTEP)
    init_logging("logfile", debug=True)
    LOGGER.info("Simulation started with command: %s", sys.argv)

    ## Network setup
    # First population
    p1 = pynnn.Population(100,
                          pynnn.IF_curr_alpha,
                          structure=pynnn.space.Grid2D())
    p1.set({'tau_m': 20, 'v_rest': -65})
    # Second population
    p2 = pynnn.Population(20,
                          pynnn.IF_curr_alpha,
                          cellparams={
                              'tau_m': 15.0,
                              'cm': 0.9
                          })
    # Projection 1 -> 2
    prj1_2 = pynnn.Projection(
        p1,
        p2,
        pynnn.AllToAllConnector(allow_self_connections=False),
        target='excitatory')
    # I may need to make own PyNN Connector class. Otherwise, this is
    # neat:  exponentially decaying probability of connections depends
    # on distance. Distance is only calculated using x and y, which
    # are on a toroidal topo with boundaries at 0 and 500.
    connector = pynnn.DistanceDependentProbabilityConnector(
        "exp(-abs(d))",
        space=pynnn.Space(axes='xy',
                          periodic_boundaries=((0, 500), (0, 500), None)))
    # Alternately, the powerful connection set algebra (python CSA
    # module) can be used.
    weight_distr = pynnn.RandomDistribution(distribution='gamma',
                                            parameters=[1, 0.1])
    prj1_2.randomizeWeights(weight_distr)

    # This one is in NEST but not in Brian:
    # source = pynnn.NoisyCurrentSource(
    #     mean=100, stdev=50, dt=SIMU_TIMESTEP,
    #     start=10.0, stop=SIMU_DURATION, rng=pynnn.NativeRNG(seed=100))
    source = pynnn.DCSource(start=10.0, stop=SIMU_DURATION, amplitude=100)
    source.inject_into(list(p1.sample(50).all()))

    p1.record(to_file=False)
    p2.record(to_file=False)

    ## Build and send the visualizable network structure
    adapter = pynn_to_visu.PynnToVisuAdapter(LOGGER)
    adapter.add_pynn_population(p1)
    adapter.add_pynn_population(p2)
    adapter.add_pynn_projection(p1, p2, prj1_2.connection_manager)
    adapter.commit_structure()

    parent_conn.send(adapter.output_struct)

    # Number of chunks to run the simulation:
    n_chunks = SIMU_DURATION // SIMU_TO_VISU_MESSAGE_PERIOD
    last_chunk_duration = SIMU_DURATION % SIMU_TO_VISU_MESSAGE_PERIOD
    # Run the simulator
    for visu_i in xrange(n_chunks):
        pynnn.run(SIMU_TO_VISU_MESSAGE_PERIOD)
        parent_conn.send(adapter.make_activity_update_message())
        LOGGER.debug("real current p1 spike counts: %s",
                     p1.get_spike_counts().values())
    if last_chunk_duration > 0:
        pynnn.run(last_chunk_duration)
        parent_conn.send(adapter.make_activity_update_message())
    # Cleanup
    pynnn.end()
    # Wait for the visualisation process to terminate
    p.join(VISU_PROCESS_JOIN_TIMEOUT)