Esempio n. 1
0
    def _activate_hln(self, sim, block_interval, firing_rate):
        next_block_tstart = (block_interval[1] +
                             1) * sim.dt  # The next time-step
        next_block_tstop = next_block_tstart + sim.nsteps_block * sim.dt  # The time-step when the next block ends

        # This is where you can use the firing-rate of the low-level neurons to generate a set of spike times for the
        # next block
        psg = PoissonSpikeGenerator()
        psg.add(node_ids=[0],
                firing_rate=firing_rate,
                times=(next_block_tstart, next_block_tstop))
        self._spike_events = psg.get_times(0)

        # Update firing rate of bladder afferent neurons
        for gid in self._high_level_neurons:
            nc = self._netcons[gid]
            for t in self._spike_events:
                nc.event(t)

        # If pressure is maxxed, update firing rate of EUS motor neurons
        # Guarding reflex
        press_change = self._prev_glob_press - self._glob_press
        if self._glob_press > press_thres or press_change > change_thres:
            psg = PoissonSpikeGenerator()
            psg.add(node_ids=[0],
                    firing_rate=150,
                    times=(next_block_tstart, next_block_tstop))
            self._spike_events = psg.get_times(0)

            for gid in self._eus_neurons:
                nc = self._netcons[gid]
                for t in self._spike_events:
                    nc.event(t)
Esempio n. 2
0
def single_proc():
    print('--NEW VERSION--')
    psg = PoissonSpikeGenerator(population='v1', seed=10)
    psg.add(node_ids=np.arange(N), firing_rate=30.0, times=3.0)

    tmph5 = tempfile.NamedTemporaryFile(suffix='.h5')
    mem = memory_usage((write_sonata, (tmph5.name, psg)))
    print(max(mem))

    tmph5 = tempfile.NamedTemporaryFile(suffix='.h5')
    start = timer()
    write_sonata(tmph5.name, psg)
    print(timer() - start)

    print('--OLD VERSION--')
    psg = PoissonSpikeGenerator(population='v1',
                                seed=10,
                                buffer_dir='tmp_spikes')
    psg.add(node_ids=np.arange(N), firing_rate=30.0, times=3.0)

    tmph5 = tempfile.NamedTemporaryFile(suffix='.h5')
    mem = memory_usage((write_sonata_old, (tmph5.name, psg)))
    print(max(mem))

    tmph5 = tempfile.NamedTemporaryFile(suffix='.h5')
    start = timer()
    write_sonata_old(tmph5.name, psg)
    print(timer() - start)
Esempio n. 3
0
    def _activate_hln(self, sim, block_interval, firing_rate):
        next_block_tstart = (block_interval[1] + 1) * sim.dt  # The next time-step
        next_block_tstop = next_block_tstart + sim.nsteps_block*sim.dt  # The time-step when the next block ends

        # This is where you can use the firing-rate of the low-level neurons to generate a set of spike times for the
        # next block
        psg = PoissonSpikeGenerator()
        psg.add(node_ids=[0], firing_rate=firing_rate/1000, times=(next_block_tstart, next_block_tstop))
        self._spike_events = psg.get_times(0)
        
        if self._spike_events.shape[0]==0:
            self._spike_events = np.array((next_block_tstart+0.2,))

        # Update firing rate of bladder afferent neurons
        for gid in self._high_level_neurons:
            nc = self._netcons[gid]
            for t in self._spike_events:
                nc.event(t)
Esempio n. 4
0
def test_psg_variable():
    times = np.linspace(0.0, 3.0, 1000)
    fr = np.exp(-np.power(times - 1.0, 2) / (2 * np.power(.5, 2))) * 5

    psg = PoissonSpikeGenerator(population='test', seed=0.0)
    psg.add(node_ids=range(10), firing_rate=fr, times=times)

    assert (psg.populations == ['test'])
    assert (np.all(psg.node_ids() == list(range(10))))
    assert (psg.n_spikes() == 59)
    assert (np.allclose(psg.time_range(),
                        (0.13932107933711294, 2.9013003727909172)))
    assert (psg.to_dataframe().shape == (59, 3))
    assert (np.allclose(psg.get_times(node_id=0),
                        [0.442, 0.520, 0.640, 1.099, 1.393, 1.725],
                        atol=1.0e-3))
    assert (np.allclose(psg.get_times(node_id=9),
                        [0.729, 0.885, 1.047, 1.276, 1.543, 1.669, 1.881],
                        atol=1.0e-3))
Esempio n. 5
0
    def _activate_hln(self, sim, block_interval, firing_rate):
        next_block_tstart = (block_interval[1] +
                             1) * sim.dt  # The next time-step
        next_block_tstop = next_block_tstart + sim.nsteps_block * sim.dt  # The time-step when the next block ends
        # TODO: See if we've reached the end of the simulation

        # This is where you can use the firing-rate of the low-level neurons to generate a set of spike times for the
        # next block. For this case I'm just setting the high-level neuron to start bursting
        #if firing_rate > firing_rate_threshold:
        #self._spike_events = np.linspace(next_block_tstart, next_block_tstop, 500)
        psg = PoissonSpikeGenerator()
        psg.add(node_ids=[0],
                firing_rate=firing_rate,
                times=(next_block_tstart, next_block_tstop))
        self._spike_events = psg.get_times(0)

        for gid in self._high_level_neurons:
            nc = self._netcons[gid]
            for t in self._spike_events:
                nc.event(t)
Esempio n. 6
0
def test_psg_fixed():
    psg = PoissonSpikeGenerator(population='test', seed=0.0)
    psg.add(node_ids=range(10), firing_rate=10.0, times=(0.0, 10.0))
    assert(psg.populations == ['test'])
    assert(psg.nodes() == list(range(10)))

    time_range = psg.time_range()
    assert(0 <= time_range[0] < 1.0)
    assert(9.0 < time_range[1] <= 10.0)

    # This may fail on certain versions
    assert(psg.get_times(node_id=5).size > 10)
    assert(0 < psg.get_times(node_id=8).size < 300)

    for i in range(10):
        spikes = psg.get_times(i)
        assert(np.max(spikes) > 0.1)
Esempio n. 7
0
def test_psg_variable():
    times = np.linspace(0.0, 3.0, 1000)
    fr = np.exp(-np.power(times - 1.0, 2) / (2 * np.power(.5, 2))) * 5

    psg = PoissonSpikeGenerator(population='test', seed=0.0)
    psg.add(node_ids=range(10), firing_rate=fr, times=times)

    assert (psg.populations == ['test'])
    assert (np.all(psg.node_ids() == list(range(10))))
    assert (psg.n_spikes() == 59)
    assert (np.allclose(psg.time_range(),
                        (139.32107933711294, 2901.3003727909172)))
    assert (psg.to_dataframe().shape == (59, 3))
    assert (np.allclose(
        psg.get_times(node_id=0),
        [442.8378, 520.3624, 640.3880, 1099.0661, 1393.0794, 1725.6109],
        atol=1.0e-3))
    assert (np.allclose(psg.get_times(node_id=9), [
        729.6267, 885.2469, 1047.7728, 1276.3554, 1543.6557, 1669.9070,
        1881.3605
    ],
                        atol=1.0e-3))
Esempio n. 8
0
def build_spike_trains(N=N_LIF_exc + N_LIF_inh):
    from bmtk.utils.reports.spike_trains import PoissonSpikeGenerator
    from bmtk.utils.reports.spike_trains import sort_order

    # Steadily increase the firing rate of each virtual cell from 1.0 Hz (node 0) to 50.0 Hz (node 12499)
    firing_rates = 500 * np.ones(N)

    psg = PoissonSpikeGenerator(population='external')
    for i in range(N):
        # create a new spike-train for each node.
        psg.add(node_ids=i, firing_rate=firing_rates[i], times=(0.0, 3.0))

    psg.to_sonata('inputs/injective_500hz.h5', sort_order=sort_order.by_id)
Esempio n. 9
0
def test_psg_variable():
    times = np.linspace(0.0, 10.0, 1000)
    fr = np.exp(-np.power(times - 5.0, 2) / (2*np.power(.5, 2)))*5

    psg = PoissonSpikeGenerator(population='test', seed=0.0)
    psg.add(node_ids=range(10), firing_rate=fr, times=times)

    assert(psg.populations == ['test'])
    assert(psg.nodes() == list(range(10)))

    for i in range(10):
        spikes = psg.get_times(i)
        assert(len(spikes) > 0)
        assert(1.0 < np.min(spikes))
        assert(np.max(spikes) < 9.0)
Esempio n. 10
0
    def _activate_hln(self, sim, block_interval, firing_rate):
        block_length = sim.nsteps_block * sim.dt / 1000.0
        next_block_tstart = (block_interval[1] +
                             1) * sim.dt / 1000.0  # The next time-step
        next_block_tstop = next_block_tstart + block_length  # The time-step when the next block ends

        # This is where you can use the firing-rate of the low-level neurons to generate a set of spike times for the
        # next block
        if firing_rate > 0.0:
            psg = PoissonSpikeGenerator()
            # # Use homogeneous input
            # psg.add(node_ids=[0], firing_rate=firing_rate, times=(next_block_tstart, next_block_tstop)) # sec
            # spikes = psg.get_times([0])*1000 # convert sec to ms
            # n_spikes = len(spikes)
            # io.log_info('     _activate_hln firing rate: {:.2f} Hz'.format(n_spikes/block_length))
            # if n_spikes > 0:
            # # Update firing rate of bladder afferent neurons
            # for gid in self._high_level_neurons:
            # self._spike_events[gid] = np.concatenate((self._spike_events[gid],spikes))
            # nc = self._netcons[gid]
            # for t in spikes:
            # nc.event(t)
            # io.log_info('Last spike: {:.1f} ms'.format(spikes[-1]))
            # Use inhomogeneous input
            n = len(self._high_level_neurons)
            psg.add(node_ids=self._high_level_neurons,
                    firing_rate=firing_rate,
                    times=(next_block_tstart, next_block_tstop))
            n_spikes = np.zeros(n)
            last_spike = 0.0
            for i, gid in enumerate(self._high_level_neurons):
                spikes = psg.get_times(gid) * 1000
                n_spikes[i] = len(spikes)
                if n_spikes[i] > 0:
                    self._spike_events[gid] = np.concatenate(
                        (self._spike_events[gid], spikes))
                    nc = self._netcons[gid]
                    for t in spikes:
                        nc.event(t)
                    last_spike = max(last_spike, spikes[-1])
            io.log_info(
                '     _activate_hln firing rate: ' +
                ','.join(["%.2f" % (ns / block_length)
                          for ns in n_spikes]) + ' Hz')
            if last_spike > 0:
                io.log_info('Last spike: {:.1f} ms'.format(last_spike))
        else:
            io.log_info('     _activate_hln firing rate: 0')

        # If pressure is maxxed, update firing rate of EUS motor neurons
        # Guarding reflex
        # press_change = self._prev_glob_press - self._glob_press
        # if self._glob_press > press_thres or press_change > change_thres:
        # psg = PoissonSpikeGenerator()
        # eus_fr = self._glob_press*10 + press_change*10 # Assumption: guarding reflex
        # # depends on current pressure
        # # and change from last pressure
        # psg.add(node_ids=[0], firing_rate=eus_fr, times=(next_block_tstart, next_block_tstop))
        # self._spike_events = psg.get_times(0)
        # for gid in self._eus_neurons:
        # nc = self._netcons[gid]
        # for t in self._spike_events:
        # nc.event(t)
################ Activate higher order based on pressure threshold ##############################

# if block_interval[1] % 2000 == 1000:  # For fast testing, only add events to every other block
# if False:  # For testing
# if self._glob_press > self.press_thres:
#     io.log_info('      updating pag input')
#     psg = PoissonSpikeGenerator()
#     print(self.press_thres)
#
#     pag_fr = self.press_thres #change
#     psg.add(node_ids=[0], firing_rate=pag_fr, times=(next_block_tstart/1000.0, next_block_tstop/1000.0))
#     if psg.n_spikes() <= 0:
#         io.log_info('     no psg spikes generated by Poisson distritubtion')
#     self._spike_events = psg.get_times(0)
#     for gid in self._pag_neurons:
#         nc = self._netcons[gid]
#         for t in self._spike_events:
#             nc.event(t)
################ Activate higher order based on afferent firing rate ##############################
        if firing_rate > 10:
            pag_fr = 15
            psg = PoissonSpikeGenerator()
            # # Use homogeneous input
            # psg.add(node_ids=[0], firing_rate=pag_fr, times=(next_block_tstart, next_block_tstop))
            # spikes = psg.get_times([0])*1000
            # n_spikes = len(spikes)
            # io.log_info('     pag firing rate: {:.2f} Hz'.format(n_spikes/block_length))
            # if n_spikes>0:
            # io.log_info('Last spike: {:.1f} ms'.format(spikes[-1]))
            # for gid in self._pag_neurons:
            # self._spike_events[gid] = np.concatenate((self._spike_events[gid],spikes))
            # nc = self._netcons[gid]
            # for t in spikes:
            # nc.event(t)
            # Use inhomogeneous input
            n = len(self._pag_neurons)
            psg.add(node_ids=self._pag_neurons,
                    firing_rate=pag_fr,
                    times=(next_block_tstart, next_block_tstop))
            n_spikes = np.zeros(n)
            last_spike = 0.0
            for i, gid in enumerate(self._pag_neurons):
                spikes = psg.get_times(gid) * 1000
                n_spikes[i] = len(spikes)
                if n_spikes[i] > 0:
                    self._spike_events[gid] = np.concatenate(
                        (self._spike_events[gid], spikes))
                    nc = self._netcons[gid]
                    for t in spikes:
                        nc.event(t)
                    last_spike = max(last_spike, spikes[-1])
            io.log_info(
                '     pag firing rate: ' +
                ','.join(["%.2f" % (ns / block_length)
                          for ns in n_spikes]) + ' Hz')
            if last_spike > 0:
                io.log_info('Last spike: {:.1f} ms'.format(last_spike))

        io.log_info('\n')
Esempio n. 11
0
thalamus.save_edges(output_dir='network')

print("External nodes and edges built")

# Build and save our network

from bmtk.utils.sim_setup import build_env_bionet

build_env_bionet(
    base_dir='./',
    network_dir='./network',
    tstop=1000.0,
    dt=0.1,
    spikes_inputs=[(
        'mthalamus',  # Name of population which spikes will be generated for
        'mthalamus_spikes.h5')],
    report_vars=['v'],  # Record membrane potential and calcium (default soma)
    components_dir='biophys_components',
    compile_mechanisms=True)

from bmtk.utils.reports.spike_trains import PoissonSpikeGenerator

psg = PoissonSpikeGenerator(population='mthalamus')
psg.add(
    node_ids=range(numL5PNA + numL5PNC +
                   numBask),  # Have nodes to match mthalamus
    firing_rate=
    15.0,  # 15 Hz, we can also pass in a nonhomoegenous function/array
    times=(0.0, 3.0))  # Firing starts at 0 s up to 3 s
psg.to_sonata('mthalamus_spikes.h5')
Esempio n. 12
0
def test_psg_fixed():
    psg = PoissonSpikeGenerator(population='test', seed=100)
    psg.add(node_ids=range(10), firing_rate=5.0, times=(0.0, 3.0))
    assert (psg.populations == ['test'])
    assert (np.all(psg.node_ids() == list(range(10))))
    assert (psg.n_spikes() == 143)
    assert (psg.n_spikes(population='test') == 143)
    assert (np.allclose(psg.time_range(),
                        (5.380662350673328, 2986.5205688893295)))

    df = psg.to_dataframe()
    assert (df.shape == (143, 3))

    assert (np.allclose(psg.get_times(node_id=0), [
        156.7916, 222.0400, 332.5493, 705.1267, 706.0727, 731.9963, 954.1834,
        1303.7542, 1333.1543, 1504.3314, 1948.2045, 1995.1471, 2036.1411,
        2059.0835, 2108.6982, 2877.7935
    ],
                        atol=1.0e-3))

    assert (np.allclose(psg.get_times(node_id=9, population='test'), [
        23.3176, 241.7332, 390.1951, 428.2215, 1001.0229, 1056.4003, 2424.8442,
        2599.6312, 2640.1228, 2737.9504, 2780.0140, 2885.8020
    ],
                        atol=1.0e-3))
Esempio n. 13
0
    #st.write(path)
    if (path != "streamlit"):
        os.chdir("streamlit")
    if os.path.isdir('biophys_components/mechanisms/x86_64'):
        shutil.rmtree('biophys_components/mechanisms/x86_64')
    os.chdir('biophys_components/mechanisms')
    os.system('nrnivmodl modfiles')
    os.chdir("../..")
    st.write("Building model")
    build_model()
    st.write("Done building")

bg_pn = st.slider('Generate PN background')
if st.button("Push to Generate"):
    os.remove('2_cell_inputs/bg_pn_c_spikes.h5')
    psg = PoissonSpikeGenerator(population='bg_pn_c')
    psg.add(
        node_ids=range(1),  # need same number as cells
        firing_rate=bg_pn,  # 1 spike every 1 second Hz
        times=(0.0, 40000 / 1000))  # time is in seconds for some reason
    psg.to_sonata('2_cell_inputs/bg_pn_c_spikes.h5')
    st.write('Generated background of PN at : {} Hz'.format(bg_pn))

if st.button("Push to run model"):
    st.write("running model")
    run(config_file='config.json')
    st.write("done running")

if st.button("Plot results"):
    _ = plot_traces(config_file='config.json',
                    node_ids=[0],
Esempio n. 14
0
# Build and save our networks
net.build()
net.save_nodes(output_dir='network')
net.save_edges(output_dir='network')

exc_stim.build()
exc_stim.save_nodes(output_dir='network')

inh_stim.build()
inh_stim.save_nodes(output_dir='network')

from bmtk.utils.reports.spike_trains import PoissonSpikeGenerator
from bmtk.utils.reports.spike_trains.spikes_file_writers import write_csv

exc_psg = PoissonSpikeGenerator(population='exc_stim')
exc_psg.add(node_ids=range(np.sum(num_exc)),
            firing_rate=int(exc_fr) / 1000,
            times=(200.0, 1200.0))
exc_psg.to_sonata('exc_stim_spikes.h5')

inh_psg = PoissonSpikeGenerator(population='inh_stim')
inh_psg.add(node_ids=range(np.sum(num_inh)),
            firing_rate=int(inh_fr) / 1000,
            times=(200.0, 1200.0))
inh_psg.to_sonata('inh_stim_spikes.h5')

from bmtk.utils.sim_setup import build_env_bionet

build_env_bionet(base_dir='./',
                 network_dir='./network',
Esempio n. 15
0
def build_input(t_sim,
                numPN_A=569,
                numPN_C=231,
                numBask=93,
                numSOM=51,
                numCR=56):
    print("Building input for " + str(t_sim) + " (ms)")
    psg = PoissonSpikeGenerator(population='vpsi_pyr')
    psg.add(
        node_ids=range(numPN_A + numPN_C),  # Have nodes to match mthalamus
        #    firing_rate=2.0,    # 15 Hz, we can also pass in a nonhomoegenous function/array
        firing_rate=lognorm_fr_list(numPN_A + numPN_C, 2, 1),
        times=(0.0, t_sim / 1000.0))  # Firing starts at 0 s up to 3 s
    psg.to_sonata('vpsi_pyr_spikes.h5')

    psg = PoissonSpikeGenerator(population='vpsi_pv')
    psg.add(
        node_ids=range(numBask),  # Have nodes to match mthalamus
        #    firing_rate=2.0,    # 15 Hz, we can also pass in a nonhomoegenous function/array
        firing_rate=lognorm_fr_list(numBask, 2, 1),
        times=(0.0, t_sim / 1000.0))  # Firing starts at 0 s up to 3 s
    psg.to_sonata('vpsi_pv_spikes.h5')

    # THALAMUS

    psg = PoissonSpikeGenerator(population='thalamus_pyr')
    psg.add(
        node_ids=range(numPN_A + numPN_C),  # Have nodes to match 
        #    firing_rate=2.0,    # 15 Hz, we can also pass in a nonhomoegenous function/array
        firing_rate=lognorm_fr_list(numPN_A + numPN_C, 4, 1),
        times=(0.0, t_sim / 1000.0))  # Firing starts at 0 s up to 3 s
    psg.to_sonata('thalamus_pyr_spikes.h5')

    psg = PoissonSpikeGenerator(population='thalamus_pv')
    psg.add(
        node_ids=range(numBask),  # Have nodes to match 
        #    firing_rate=2.0,    # 15 Hz, we can also pass in a nonhomoegenous function/array
        firing_rate=lognorm_fr_list(numBask, 2, 1),
        times=(0.0, t_sim / 1000.0))  # Firing starts at 0 s up to 3 s
    psg.to_sonata('thalamus_pv_spikes.h5')

    psg = PoissonSpikeGenerator(population='thalamus_som')
    psg.add(
        node_ids=range(numSOM),  # Have nodes to match 
        #    firing_rate=2.0,    # 15 Hz, we can also pass in a nonhomoegenous function/array
        firing_rate=lognorm_fr_list(numSOM, 2, 1),
        times=(0.0, t_sim / 1000.0))  # Firing starts at 0 s up to 3 s
    psg.to_sonata('thalamus_som_spikes.h5')

    psg = PoissonSpikeGenerator(population='thalamus_cr')
    psg.add(
        node_ids=range(numCR),  # Have nodes to match 
        #    firing_rate=2.0,    # 15 Hz, we can also pass in a nonhomoegenous function/array
        firing_rate=lognorm_fr_list(numCR, 2, 1),
        times=(0.0, t_sim / 1000.0))  # Firing starts at 0 s up to 3 s
    psg.to_sonata('thalamus_cr_spikes.h5')

    print("Done")
Esempio n. 16
0
    def _activate_hln(self, sim, block_interval, firing_rate):
        next_block_tstart = (block_interval[1] + 1) * sim.dt  # The next time-step
        next_block_tstop = next_block_tstart + sim.nsteps_block*sim.dt  # The time-step when the next block ends

        # This is where you can use the firing-rate of the low-level neurons to generate a set of spike times for the
        # next block
        if firing_rate != 0.0:
            psg = PoissonSpikeGenerator()
            psg.add(node_ids=[0], firing_rate=firing_rate, times=(next_block_tstart/1000.0, next_block_tstop/1000.0))
            if psg.n_spikes() <= 0:
                io.log_info('     _activate_hln: firing rate {} did not produce any spikes'.format(firing_rate))
            else:
                self._spike_events = psg.get_times(0)
                # Update firing rate of bladder afferent neurons
                for gid in self._high_level_neurons:
                    nc = self._netcons[gid]
                    for t in self._spike_events:
                        nc.event(t)
        else:
            io.log_info('     _activate_hln: firing rate 0')

        # If pressure is maxxed, update firing rate of EUS motor neurons 
        # Guarding reflex
        # press_change = self._prev_glob_press - self._glob_press
        # if self._glob_press > press_thres or press_change > change_thres:
            # psg = PoissonSpikeGenerator()
            # eus_fr = self._glob_press*10 + press_change*10 # Assumption: guarding reflex
                                                           # # depends on current pressure
                                                           # # and change from last pressure
            # psg.add(node_ids=[0], firing_rate=eus_fr, times=(next_block_tstart, next_block_tstop))
            # self._spike_events = psg.get_times(0)
            # for gid in self._eus_neurons:
                # nc = self._netcons[gid]
                # for t in self._spike_events:
                    # nc.event(t)
################ Activate higher order based on pressure threshold ##############################

        # if block_interval[1] % 2000 == 1000:  # For fast testing, only add events to every other block
        # if False:  # For testing
        if self._glob_press > self.press_thres:
            io.log_info('      updating pag input')
            psg = PoissonSpikeGenerator()
            print(self.press_thres)

            pag_fr = self.press_thres #change
            psg.add(node_ids=[0], firing_rate=pag_fr, times=(next_block_tstart/1000.0, next_block_tstop/1000.0))
            if psg.n_spikes() <= 0:
                io.log_info('     no psg spikes generated by Poisson distritubtion')
            self._spike_events = psg.get_times(0)
            for gid in self._pag_neurons:
                nc = self._netcons[gid]
                for t in self._spike_events:
                    nc.event(t)
Esempio n. 17
0
import os
from bmtk.utils.reports.spike_trains import PoissonSpikeGenerator

if not os.path.exists('inputs'):
    os.mkdir('inputs')

psg = PoissonSpikeGenerator(population='external')
psg.add(
    node_ids=range(100),
    firing_rate=10.0,
)
psg.add(node_ids=range(100), firing_rate=10.0, times=(0.0, 3.0))
psg.to_sonata('inputs/external_spike_trains.h5')
                   target=net.nodes(pop_name=['Int']),
                   connection_rule=1,
                   syn_weight=1,
                   delay=2.0,
                   weight_function=None,
                   target_sections=['somatic'],
                   distance_range=[0.0, 150.0],
                   dynamics_params='AMPA_ExcToExc.json',
                   model_template='exp2syn')

net.build()
net.save(output_dir='network')
thalamus.build()
thalamus.save(output_dir='network')

psg = PoissonSpikeGenerator(population='mthalamus')
psg.add(
    node_ids=1,  # Have 5 nodes to match mthalamus
    firing_rate=8,  # 2 Hz
    times=(0.0, 1))  # time is in seconds for some reason
psg.to_sonata('virtual_spikes.h5')
print('Number of background spikes: {}'.format(psg.n_spikes()))

from bmtk.utils.sim_setup import build_env_bionet
build_env_bionet(
    base_dir='../',
    network_dir='./network',
    tstop=1000.0,
    dt=0.1,
    report_vars=['v'],
    spikes_inputs=[('mthalamus', 'virtual_spikes.h5')],
Esempio n. 19
0
def test_psg_fixed():
    psg = PoissonSpikeGenerator(population='test', seed=100)
    psg.add(node_ids=range(10), firing_rate=5.0, times=(0.0, 3.0))
    assert (psg.populations == ['test'])
    assert (np.all(psg.node_ids() == list(range(10))))
    assert (psg.n_spikes() == 143)
    assert (psg.n_spikes(population='test') == 143)
    assert (np.allclose(psg.time_range(),
                        (0.005380662350673328, 2.9865205688893295)))

    df = psg.to_dataframe()
    assert (df.shape == (143, 3))

    assert (np.allclose(psg.get_times(node_id=0), [
        0.156, 0.222, 0.332, 0.705, 0.706, 0.731, 0.954, 1.303, 1.333, 1.504,
        1.948, 1.995, 2.036, 2.059, 2.108, 2.877
    ],
                        atol=1.0e-3))
    assert (np.allclose(psg.get_times(node_id=9, population='test'), [
        0.0233, 0.241, 0.390, 0.428, 1.001, 1.056, 2.424, 2.599, 2.640, 2.737,
        2.780, 2.885
    ],
                        atol=1.0e-3))
Esempio n. 20
0
    distance_range=[0.0, 150.0],
    # Set the parameters of the synpases
    dynamics_params=
    'AMPA_ExcToExc.json',  # AMPA type synaptic model with an Excitatory connection
    model_template='exp2syn')

# Build thalamus (saving nodes and edges)
thalamus.build()
thalamus.save_nodes(output_dir='%s/network' % (savedir))
thalamus.save_edges(output_dir='%s/network' % (savedir))

# Set spike trains
from bmtk.utils.reports.spike_trains import PoissonSpikeGenerator

spikesFilename = '%s/inputs/mthalamus_spikes.h5' % (savedir)
psg = PoissonSpikeGenerator(population='mthalamus')
psg.add(
    node_ids=range(10),  # Have 10 nodes to match mthalamus
    firing_rate=
    15.0,  # 10 Hz, we can also pass in a nonhomoegenous function/array
    times=(0.0, 3.0))  # Firing starts at 0 s up to 3 s
if not (os.path.isfile(spikesFilename)):
    psg.to_sonata(spikesFilename)

# ----------------------------------------------------
# 2. Set up the BioNet environment
# ----------------------------------------------------
'''Before running a simulation, we will need to create the runtime environment, including parameter files, run-script
and configuration files. This will also compile mechanisms'''

# Mechanisms need to be compiled?
Esempio n. 21
0
import os
from bmtk.utils.reports.spike_trains import PoissonSpikeGenerator
from bmtk.utils.reports.spike_trains import SpikeTrains
import matplotlib.pyplot as plt
import numpy as np

if os.path.exists('inputs/ramping_spikes.h5'):
    os.remove('inputs/ramping_spikes.h5')

# Create PGN firing rate
time_range = np.linspace(0.0, 10.0, 20000)
psg = PoissonSpikeGenerator(mode='w')
psg.add(node_ids=[0],
        firing_rate=np.linspace(1.0, 10.0, 30000),
        population='external',
        times=time_range)
psg.to_sonata('inputs/ramping_spikes.h5')

#st = SpikeTrains.from_sonata('inputs/ramping_spikes.h5')
#print(st.get_times(0))
#spikes = np.zeros(100001, dtype=np.int)
#spikes[(st.get_times(0) / 0.1).astype(np.int)] = 1
#plt.plot(spikes)
#plt.show()
Esempio n. 22
0
from bmtk.utils.reports.spike_trains import SpikeTrains, PoissonSpikeGenerator

# A constant firing rate of 10 Hz from 0 to 3 seconds
times = (0.0, 3.0)
firing_rate = 10.0

## Uncomment to model the input firing rates on a sin wave
# times = np.linspace(0.0, 3.0, 1000)
# firing_rate = 10.0*np.sin(times) + 10.0

psg = PoissonSpikeGenerator()  # Uses 'seed' to ensure same results every time
psg.add(node_ids='network/thalamus_nodes.h5', firing_rate=firing_rate, times=times, population='thalamus')
psg.to_sonata('thalamus.h5')
psg.to_csv('thalamus.csv')
Esempio n. 23
0
def build_input(t_sim, numPN_A=640, numPN_C=260, numBask=100):
    print("Building input for " + str(t_sim) + " (ms)")
    psg = PoissonSpikeGenerator(population='mthalamus')
    psg.add(
        node_ids=range(numPN_A + numPN_C),  # Have nodes to match mthalamus
        #    firing_rate=2.0,    # 15 Hz, we can also pass in a nonhomoegenous function/array
        firing_rate=lognorm_fr_list(numPN_A + numPN_C, 2, 1),
        times=(0.0, t_sim / 1000.0))  # Firing starts at 0 s up to 3 s
    psg.to_sonata('mthalamus_spikes.h5')

    psg = PoissonSpikeGenerator(population='exc_bg_bask')
    psg.add(
        node_ids=range(numBask),  # Have nodes to match mthalamus
        #    firing_rate=2.0,    # 15 Hz, we can also pass in a nonhomoegenous function/array
        firing_rate=lognorm_fr_list(numBask, 2, 1),
        times=(0.0, t_sim / 1000.0))  # Firing starts at 0 s up to 3 s
    psg.to_sonata('exc_bg_bask_spikes.h5')
    print("Done")
Esempio n. 24
0
# fr_df['gid'] = [i for i in range(N)]
# fr_df['fr_mean'] = exc_means
# fr_df['fr_std'] = exc_stds
# fr_df['fr_max'] = exc_maxs

#fr_df.to_csv('frs_temp.csv', index=False)
seconds = 1


def generate_spikes(psg, group, fr, times):
    psg.add(node_ids=range(group.start_id, group.start_id + len(group.cells)),
            firing_rate=fr,
            times=times)


exc_psg = PoissonSpikeGenerator(population='exc_stim')
exc_psg.add(node_ids=range(num_apic_exc + num_dend_exc),
            firing_rate=0.01,
            times=(0.0 * 1000, seconds * 1000))
exc_psg.to_sonata('exc_stim_spikes.h5')
# exc_psg = PoissonSpikeGenerator(population='exc_stim')
# for i in range(num_exc):
#         exc_psg.add(node_ids=[i],
#                 firing_rate=exc_frs[i]/1000,
#                 times=(0.0*1000, seconds*1000))
# exc_psg.to_sonata('exc_stim_spikes.h5')

# inh_psg = PoissonSpikeGenerator(population='inh_stim')
# inh_psg.add(node_ids=range(num_inh),
#         firing_rate=inh_fr/1000,
#         times=(0.0*1000, seconds*1000))
Esempio n. 25
0
from bmtk.utils.sim_setup import build_env_bionet

build_env_bionet(base_dir='./',
                 network_dir='./network',
                 tstop=t_sim, dt=0.1,
                 spikes_inputs=[('mthalamus', 'mthalamus_spikes.h5'),
                                ('exc_bg_bask', 'exc_bg_bask_spikes.h5'),
                                ('exc_bg_chn', 'exc_bg_chn_spikes.h5')],
                 components_dir='biophys_components',
                 compile_mechanisms=True)

from bmtk.utils.reports.spike_trains import PoissonSpikeGenerator

#
psg = PoissonSpikeGenerator(population='mthalamus')
psg.add(node_ids=range(numPN_A + numPN_C),  # Have nodes to match mthalamus
        firing_rate=0.2,  # 15 Hz, we can also pass in a nonhomoegenous function/array
        times=(0.0, t_sim))  # Firing starts at 0 s up to 3 s
psg.to_sonata('mthalamus_spikes.h5')

psg = PoissonSpikeGenerator(population='exc_bg_bask')
psg.add(node_ids=range(numBask),  # Have nodes to match mthalamus
        firing_rate=0.2,  # 15 Hz, we can also pass in a nonhomoegenous function/array
        times=(0.0, t_sim))  # Firing starts at 0 s up to 3 s
psg.to_sonata('exc_bg_bask_spikes.h5')

psg = PoissonSpikeGenerator(population='exc_bg_chn')
psg.add(node_ids=range(numAAC),  # Have nodes to match mthalamus
        firing_rate=0.2,  # 15 Hz, we can also pass in a nonhomoegenous function/array
        times=(0.0, t_sim))  # Firing starts at 0 s up to 3 s
Esempio n. 26
0
net.build()
net.save(output_dir='network')
# SPIKE TRAINS
t_sim = 40000

#build_env_bionet(base_dir='./',
#                 network_dir='./network',
#                 tstop=t_sim, dt=0.1,
#                 report_vars=['v'],
#                 components_dir='biophys_components',
#                 config_file='config.json',
#                 spikes_inputs=[('bg_pn_c', '2_cell_inputs/bg_pn_c_spikes.h5'),
#                                ('bg_pv', '2_cell_inputs/bg_pv_spikes.h5')],
#                 compile_mechanisms=False)

psg = PoissonSpikeGenerator(population='bg_pn_c')
psg.add(
    node_ids=range(1),  # need same number as cells
    firing_rate=6,  # 1 spike every 1 second Hz
    times=(0.0, t_sim / 1000))  # time is in seconds for some reason
psg.to_sonata('2_cell_inputs/bg_pn_c_spikes.h5')

print('Number of background spikes for PN_C: {}'.format(psg.n_spikes()))

psg = PoissonSpikeGenerator(population='bg_pv')
psg.add(
    node_ids=range(1),  # need same number as cells
    firing_rate=7.7,  # 8 spikes every 1 second Hz
    times=(0.0, t_sim / 1000))  # time is in seconds for some reason
psg.to_sonata('2_cell_inputs/bg_pv_spikes.h5')
Esempio n. 27
0
        exc_means.append(np.mean(frs))
        exc_stds.append(np.std(frs))
        exc_maxs.append(np.max(frs))

exc_frs = exc_dend_frs + exc_apic_frs
fr_df = pd.DataFrame()
#fr_df['gid'] = [i + num_exc+num_inh for i in range(N)]
fr_df['gid'] = [i for i in range(N)]
fr_df['fr_mean'] = exc_means
fr_df['fr_std'] = exc_stds
fr_df['fr_max'] = exc_maxs

fr_df.to_csv('frs_temp.csv', index=False)

exc_psg = PoissonSpikeGenerator(population='exc_stim')
for i in range(num_exc):
        exc_psg.add(node_ids=[i],  
                firing_rate=float(exc_frs[i]/1000),    
                times=(1.0*1000, 4.0*1000))     
exc_psg.to_sonata('exc_stim_spikes.h5')

inh_psg = PoissonSpikeGenerator(population='inh_stim')
inh_psg.add(node_ids=range(num_inh), 
        firing_rate=inh_fr/1000,  
        times=(1.0*1000, 4.0*1000))   
inh_psg.to_sonata('inh_stim_spikes.h5')


from bmtk.utils.sim_setup import build_env_bionet
Esempio n. 28
0
def build_model():
    if os.path.isdir('network'):
        shutil.rmtree('network')
    if os.path.isdir('2_cell_inputs'):
        shutil.rmtree('2_cell_inputs')

    seed = 967
    random.seed(seed)
    np.random.seed(seed)
    load()
    syn = syn_params_dicts()

    # Initialize our network

    net = NetworkBuilder("biophysical")

    num_inh = [1]

    num_exc = [1]

    ##################################################################################
    ###################################BIOPHY#########################################

    # PN
    net.add_nodes(N=1,
                  pop_name='PyrC',
                  mem_potential='e',
                  model_type='biophysical',
                  model_template='hoc:Cell_C',
                  morphology=None)

    # PV
    net.add_nodes(N=1,
                  pop_name="PV",
                  mem_potential='e',
                  model_type='biophysical',
                  model_template='hoc:basket',
                  morphology=None)

    backgroundPN_C = NetworkBuilder('bg_pn_c')
    backgroundPN_C.add_nodes(N=1,
                             pop_name='tON',
                             potential='exc',
                             model_type='virtual')

    backgroundPV = NetworkBuilder('bg_pv')
    backgroundPV.add_nodes(N=2,
                           pop_name='tON',
                           potential='exc',
                           model_type='virtual')

    # if neuron is sufficiently depolorized enough post synaptic calcium then synaptiic weight goes up

    # pyr->pyr & pyr->PV
    # PV->pyr PV->PV
    def one_to_all(source, target):
        sid = source.node_id
        tid = target.node_id
        print("connecting bio cell {} to bio cell {}".format(sid, tid))
        return 1

    def BG_to_PN_C(source, target):
        sid = source.node_id
        tid = target.node_id
        if sid == tid:
            print("connecting BG {} to PN_C{}".format(sid, tid))
            return 1
        else:
            return 0

    def BG_to_PV(source, target):
        sid = source.node_id
        tid = target.node_id
        sid = sid + 1
        if sid == tid:
            print("connecting BG {} to PV{}".format(sid, tid))
            return 1
        else:
            return 0

    conn = net.add_edges(source=net.nodes(pop_name='PyrC'),
                         target=net.nodes(pop_name="PV"),
                         connection_rule=one_to_all,
                         syn_weight=1.0,
                         delay=0.1,
                         distance_range=[-10000, 10000],
                         dynamics_params='PN2PV.json',
                         model_template=syn['PN2PV.json']['level_of_detail'])
    conn.add_properties(['sec_id', 'sec_x'],
                        rule=(1, 0.9),
                        dtypes=[np.int32, np.float])

    conn = net.add_edges(source=net.nodes(pop_name='PV'),
                         target=net.nodes(pop_name="PyrC"),
                         connection_rule=one_to_all,
                         syn_weight=1.0,
                         delay=0.1,
                         distance_range=[-10000, 10000],
                         dynamics_params='PV2PN.json',
                         model_template=syn['PV2PN.json']['level_of_detail'])
    conn.add_properties(['sec_id', 'sec_x'],
                        rule=(1, 0.9),
                        dtypes=[np.int32, np.float])

    conn = net.add_edges(source=backgroundPN_C.nodes(),
                         target=net.nodes(pop_name='PyrC'),
                         connection_rule=BG_to_PN_C,
                         syn_weight=1.0,
                         delay=0.1,
                         distance_range=[-10000, 10000],
                         dynamics_params='BG2PNC.json',
                         model_template=syn['BG2PNC.json']['level_of_detail'])
    conn.add_properties(['sec_id', 'sec_x'],
                        rule=(2, 0.9),
                        dtypes=[np.int32,
                                np.float])  # places syn on apic at 0.9

    conn = net.add_edges(source=backgroundPV.nodes(),
                         target=net.nodes(pop_name='PV'),
                         connection_rule=BG_to_PV,
                         syn_weight=1.0,
                         delay=0.1,
                         distance_range=[-10000, 10000],
                         dynamics_params='BG2PV.json',
                         model_template=syn['BG2PV.json']['level_of_detail'])
    conn.add_properties(['sec_id', 'sec_x'],
                        rule=(1, 0.9),
                        dtypes=[np.int32, np.float])

    backgroundPN_C.build()
    backgroundPN_C.save_nodes(output_dir='network')

    backgroundPV.build()
    backgroundPV.save_nodes(output_dir='network')

    net.build()
    net.save(output_dir='network')
    # SPIKE TRAINS
    t_sim = 40000

    # build_env_bionet(base_dir='./',
    #                 network_dir='./network',
    #                 tstop=t_sim, dt=0.1,
    #                 report_vars=['v'],
    #                 components_dir='biophys_components',
    #                 config_file='config.json',
    #                 spikes_inputs=[('bg_pn_c', '2_cell_inputs/bg_pn_c_spikes.h5'),
    #                                ('bg_pv', '2_cell_inputs/bg_pv_spikes.h5')],
    #                 compile_mechanisms=False)

    psg = PoissonSpikeGenerator(population='bg_pn_c')
    psg.add(
        node_ids=range(1),  # need same number as cells
        firing_rate=6,  # 1 spike every 1 second Hz
        times=(0.0, t_sim / 1000))  # time is in seconds for some reason
    psg.to_sonata('2_cell_inputs/bg_pn_c_spikes.h5')

    print('Number of background spikes for PN_C: {}'.format(psg.n_spikes()))

    psg = PoissonSpikeGenerator(population='bg_pv')
    psg.add(
        node_ids=range(1),  # need same number as cells
        firing_rate=7.7,  # 8 spikes every 1 second Hz
        times=(0.0, t_sim / 1000))  # time is in seconds for some reason
    psg.to_sonata('2_cell_inputs/bg_pv_spikes.h5')

    print('Number of background spikes for PV: {}'.format(psg.n_spikes()))
print("stim time is set to %s" % t_sim)

#build_env_bionet(base_dir='./',
#                 network_dir='./network',
#                 tstop=t_sim, dt=0.1,
#                 report_vars=['v'],
#                 spikes_inputs=[('tone', './12_cell_inputs/tone_spikes.csv'),
#                                ('shock', './12_cell_inputs/shock_spikes.csv'),
#                                ('bg_pn', '12_cell_inputs/bg_pn_spikes.h5'),
#                                ('bg_pv', '12_cell_inputs/bg_pv_spikes.h5'),
#                                ('bg_olm', '12_cell_inputs/bg_olm_spikes.h5')],
#                 components_dir='biophys_components',
#                 config_file='config.json',
#                 compile_mechanisms=False)

psg = PoissonSpikeGenerator(population='bg_pn')
psg.add(
    node_ids=range(8),  # need same number as cells
    firing_rate=1,  # 1 spike every 1 second Hz
    times=(0.0, t_sim / 1000))  # time is in seconds for some reason
psg.to_sonata('12_cell_inputs/bg_pn_spikes.h5')

print('Number of background spikes for pn: {}'.format(psg.n_spikes()))

psg = PoissonSpikeGenerator(population='bg_pv')
psg.add(
    node_ids=range(2),  # need same number as cells
    firing_rate=8,  # 8 spikes every 1 second Hz
    times=(0.0, t_sim / 1000))  # time is in seconds for some reason
psg.to_sonata('12_cell_inputs/bg_pv_spikes.h5')
Esempio n. 30
0
from bmtk.utils.reports.spike_trains import PoissonSpikeGenerator

psg = PoissonSpikeGenerator(population='LGN')
psg.add(
    node_ids=range(0, 100),
    firing_rate=8.0,  # we can also pass in a nonhomoegenous function/array
    times=(0.0, 2.0)  # Firing starts at 0 s up to 3 s
)

psg.to_sonata('inputs/lgn_spikes.poisson.h5')
psg.to_csv('inputs/lgn_spikes.poisson.csv')