Ejemplo n.º 1
0
def test_spikes():
    """Test spikes object."""

    # Round-trip test
    spiketimes = [[2.3456, 7.89], [4.2812, 93.2]]
    spikegids = [[1, 3], [5, 7]]
    spiketypes = [['L2_pyramidal', 'L2_basket'], ['L5_pyramidal', 'L5_basket']]
    spikes = Spikes(times=spiketimes, gids=spikegids, types=spiketypes)
    spikes.write('/tmp/spk_%d.txt')
    assert spikes == read_spikes('/tmp/spk_*.txt')
    assert ("Spikes | 2 simulation trials" in repr(spikes))

    with pytest.raises(TypeError, match="times should be a list of lists"):
        spikes = Spikes(times=([2.3456, 7.89], [4.2812, 93.2]),
                        gids=spikegids,
                        types=spiketypes)

    with pytest.raises(TypeError, match="times should be a list of lists"):
        spikes = Spikes(times=[1, 2], gids=spikegids, types=spiketypes)

    with pytest.raises(ValueError,
                       match="times, gids, and types should be "
                       "lists of the same length"):
        spikes = Spikes(times=[[2.3456, 7.89]],
                        gids=spikegids,
                        types=spiketypes)

    # Write spike file with no 'types' column
    # Check for gid_dict errors
    for fname in sorted(glob('/tmp/spk_*.txt')):
        times_gids_only = np.loadtxt(fname, dtype=str)[:, (0, 1)]
        np.savetxt(fname, times_gids_only, delimiter='\t', fmt='%s')
    with pytest.raises(ValueError,
                       match="gid_dict must be provided if spike "
                       "types are unspecified in the file /tmp/spk_0.txt"):
        spikes = read_spikes('/tmp/spk_*.txt')
    with pytest.raises(ValueError,
                       match="gid_dict should contain only "
                       "disjoint sets of gid values"):
        gid_dict = {
            'L2_pyramidal': range(3),
            'L2_basket': range(2, 4),
            'L5_pyramidal': range(4, 6),
            'L5_basket': range(6, 8)
        }
        spikes = read_spikes('/tmp/spk_*.txt', gid_dict=gid_dict)
Ejemplo n.º 2
0
def read_spktrials(sim_dir, gid_ranges):
    spk_fname_pattern = os.path.join(sim_dir, 'spk_*.txt')
    if len(glob(str(spk_fname_pattern))) == 0:
        # if legacy HNN only ran one trial, then no spk_0.txt gets written
        spk_fname_pattern = get_fname(sim_dir, 'rawspk')

    try:
        spikes = read_spikes(spk_fname_pattern, gid_ranges)
    except FileNotFoundError:
        print('Warning: could not read file:', spk_fname_pattern)

    return spikes
Ejemplo n.º 3
0
def test_cell_response(tmpdir):
    """Test CellResponse object."""

    # Round-trip test
    spike_times = [[2.3456, 7.89], [4.2812, 93.2]]
    spike_gids = [[1, 3], [5, 7]]
    spike_types = [['L2_pyramidal', 'L2_basket'],
                   ['L5_pyramidal', 'L5_basket']]
    tstart, tstop, fs = 0.1, 98.4, 1000.
    sim_times = np.arange(tstart, tstop, 1 / fs)
    gid_ranges = {
        'L2_pyramidal': range(1, 2),
        'L2_basket': range(3, 4),
        'L5_pyramidal': range(5, 6),
        'L5_basket': range(7, 8)
    }
    cell_response = CellResponse(spike_times=spike_times,
                                 spike_gids=spike_gids,
                                 spike_types=spike_types,
                                 times=sim_times)
    cell_response.plot_spikes_hist(show=False)
    cell_response.write(tmpdir.join('spk_%d.txt'))
    assert cell_response == read_spikes(tmpdir.join('spk_*.txt'))
    assert ("CellResponse | 2 simulation trials" in repr(cell_response))

    # reset clears all recorded variables, but leaves simulation time intact
    assert len(cell_response.times) == len(sim_times)
    sim_attributes = [
        '_spike_times', '_spike_gids', '_spike_types', '_vsoma', '_isoma'
    ]
    net_attributes = ['_times', '_cell_type_names']  # `Network.__init__`
    # creates these check that we always know which response attributes are
    # simulated see #291 for discussion; objective is to keep cell_response
    # size small
    assert list(cell_response.__dict__.keys()) == \
        sim_attributes + net_attributes

    # Test recovery of empty spike files
    empty_spike = CellResponse(spike_times=[[], []],
                               spike_gids=[[], []],
                               spike_types=[[], []])
    empty_spike.write(tmpdir.join('empty_spk_%d.txt'))
    assert empty_spike == read_spikes(tmpdir.join('empty_spk_*.txt'))

    assert ("CellResponse | 2 simulation trials" in repr(empty_spike))

    with pytest.raises(TypeError,
                       match="spike_times should be a list of lists"):
        cell_response = CellResponse(spike_times=([2.3456,
                                                   7.89], [4.2812, 93.2]),
                                     spike_gids=spike_gids,
                                     spike_types=spike_types)

    with pytest.raises(TypeError,
                       match="spike_times should be a list of lists"):
        cell_response = CellResponse(spike_times=[1, 2],
                                     spike_gids=spike_gids,
                                     spike_types=spike_types)

    with pytest.raises(ValueError,
                       match="spike times, gids, and types should "
                       "be lists of the same length"):
        cell_response = CellResponse(spike_times=[[2.3456, 7.89]],
                                     spike_gids=spike_gids,
                                     spike_types=spike_types)

    cell_response = CellResponse(spike_times=spike_times,
                                 spike_gids=spike_gids,
                                 spike_types=spike_types)

    with pytest.raises(TypeError,
                       match="indices must be int, slice, or "
                       "array-like, not str"):
        cell_response['1']

    with pytest.raises(TypeError,
                       match="indices must be int, slice, or "
                       "array-like, not float"):
        cell_response[1.0]

    with pytest.raises(ValueError, match="ndarray cannot exceed 1 dimension"):
        cell_response[np.array([[1, 2], [3, 4]])]

    with pytest.raises(TypeError,
                       match="gids must be of dtype int, "
                       "not float64"):
        cell_response[np.array([1, 2, 3.0])]

    with pytest.raises(TypeError,
                       match="gids must be of dtype int, "
                       "not float64"):
        cell_response[[0, 1, 2, 2.0]]

    with pytest.raises(TypeError,
                       match="spike_types should be str, "
                       "list, dict, or None"):
        cell_response.plot_spikes_hist(spike_types=1, show=False)

    with pytest.raises(TypeError,
                       match=r"spike_types\[ev\] must be a list\. "
                       r"Got int\."):
        cell_response.plot_spikes_hist(spike_types={'ev': 1}, show=False)

    with pytest.raises(ValueError,
                       match=r"Elements of spike_types must map to"
                       r" mutually exclusive input types\. L2_basket is found"
                       r" more than once\."):
        cell_response.plot_spikes_hist(
            spike_types={'ev': ['L2_basket', 'L2_b']}, show=False)

    with pytest.raises(ValueError, match="No input types found for ABC"):
        cell_response.plot_spikes_hist(spike_types='ABC', show=False)

    with pytest.raises(ValueError,
                       match="tstart and tstop must be of type "
                       "int or float"):
        cell_response.mean_rates(tstart=0.1,
                                 tstop='ABC',
                                 gid_ranges=gid_ranges)

    with pytest.raises(ValueError, match="tstop must be greater than tstart"):
        cell_response.mean_rates(tstart=0.1, tstop=-1.0, gid_ranges=gid_ranges)

    with pytest.raises(ValueError,
                       match="Invalid mean_type. Valid "
                       "arguments include 'all', 'trial', or 'cell'."):
        cell_response.mean_rates(tstart=tstart,
                                 tstop=tstop,
                                 gid_ranges=gid_ranges,
                                 mean_type='ABC')

    test_rate = (1 / (tstop - tstart)) * 1000

    assert cell_response.mean_rates(tstart, tstop, gid_ranges) == {
        'L5_pyramidal': test_rate / 2,
        'L5_basket': test_rate / 2,
        'L2_pyramidal': test_rate / 2,
        'L2_basket': test_rate / 2
    }
    assert cell_response.mean_rates(tstart,
                                    tstop,
                                    gid_ranges,
                                    mean_type='trial') == {
                                        'L5_pyramidal': [0.0, test_rate],
                                        'L5_basket': [0.0, test_rate],
                                        'L2_pyramidal': [test_rate, 0.0],
                                        'L2_basket': [test_rate, 0.0]
                                    }
    assert cell_response.mean_rates(tstart,
                                    tstop,
                                    gid_ranges,
                                    mean_type='cell') == {
                                        'L5_pyramidal': [[0.0], [test_rate]],
                                        'L5_basket': [[0.0], [test_rate]],
                                        'L2_pyramidal': [[test_rate], [0.0]],
                                        'L2_basket': [[test_rate], [0.0]]
                                    }

    # Write spike file with no 'types' column
    for fname in sorted(glob(str(tmpdir.join('spk_*.txt')))):
        times_gids_only = np.loadtxt(fname, dtype=str)[:, (0, 1)]
        np.savetxt(fname, times_gids_only, delimiter='\t', fmt='%s')

    # Check that spike_types are updated according to gid_ranges
    cell_response = read_spikes(tmpdir.join('spk_*.txt'),
                                gid_ranges=gid_ranges)
    assert cell_response.spike_types == spike_types

    # Check for gid_ranges errors
    with pytest.raises(ValueError,
                       match="gid_ranges must be provided if "
                       "spike types are unspecified in the file "):
        cell_response = read_spikes(tmpdir.join('spk_*.txt'))
    with pytest.raises(ValueError,
                       match="gid_ranges should contain only "
                       "disjoint sets of gid values"):
        gid_ranges = {
            'L2_pyramidal': range(3),
            'L2_basket': range(2, 4),
            'L5_pyramidal': range(4, 6),
            'L5_basket': range(6, 8)
        }
        cell_response = read_spikes(tmpdir.join('spk_*.txt'),
                                    gid_ranges=gid_ranges)
Ejemplo n.º 4
0
plt.figure(figsize=(4, 4), constrained_layout=True)
plt.plot(net.cell_response.times, vsoma[gid])
plt.title('%s (gid=%d)' % (net.gid_to_type(gid), gid))
plt.xlabel('Time (ms)')
plt.ylabel('Voltage (mV)')
plt.show()

###############################################################################
# Also, we can plot the spikes in the network and write them to text files.
# Note that we can use formatting syntax to specify the filename pattern
# with which each trial will be written ('spk_1.txt', 'spk_2.txt, ...). To
# read spikes back in, we can use wildcard expressions.
net.cell_response.plot_spikes_raster()
with tempfile.TemporaryDirectory() as tmp_dir_name:
    net.cell_response.write(op.join(tmp_dir_name, 'spk_%d.txt'))
    cell_response = read_spikes(op.join(tmp_dir_name, 'spk_*.txt'))
cell_response.plot_spikes_raster()

###############################################################################
# We can additionally calculate the mean spike rates for each cell class by
# specifying a time window with ``tstart`` and ``tstop``.
all_rates = cell_response.mean_rates(tstart=0,
                                     tstop=170,
                                     gid_ranges=net.gid_ranges,
                                     mean_type='all')
trial_rates = cell_response.mean_rates(tstart=0,
                                       tstop=170,
                                       gid_ranges=net.gid_ranges,
                                       mean_type='trial')
print('Mean spike rates across trials:')
print(all_rates)
Ejemplo n.º 5
0
###############################################################################
# and then plot it
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 1, sharex=True, figsize=(6, 6))
plot_dipole(dpls, ax=axes[0], layer='agg', show=False)
net.plot_input(ax=axes[1])

###############################################################################
# Also, we can plot the spikes and write them to txt files.
# Note that we can use formatting syntax to specify the filename pattern
# with which each trial will be written. To read spikes back in, we can use
# wildcard expressions.
net.spikes.plot()
with tempfile.TemporaryDirectory() as tmp_dir_name:
    net.spikes.write(op.join(tmp_dir_name, 'spk_%d.txt'))
    spikes = read_spikes(op.join(tmp_dir_name, 'spk_*.txt'))
spikes.plot()

###############################################################################
# Now, let us try to make the exogenous driving inputs to the cells
# synchronous and see what happens

params.update({'sync_evinput': True})
net_sync = Network(params)

###############################################################################
# Next, let's simulate a single trial using the MPI backend. This will
# start the simulation trial across the number of processors (cores)
# specified by n_procs using MPI. The 'mpiexec' launcher is for
# openmpi, which must be installed on the system
from hnn_core import MPIBackend
Ejemplo n.º 6
0
def test_spikes():
    """Test spikes object."""

    # Round-trip test
    spiketimes = [[2.3456, 7.89], [4.2812, 93.2]]
    spikegids = [[1, 3], [5, 7]]
    spiketypes = [['L2_pyramidal', 'L2_basket'], ['L5_pyramidal', 'L5_basket']]
    spikes = Spikes(times=spiketimes, gids=spikegids, types=spiketypes)
    spikes.plot_hist(show=False)
    spikes.write('/tmp/spk_%d.txt')
    assert spikes == read_spikes('/tmp/spk_*.txt')
    assert ("Spikes | 2 simulation trials" in repr(spikes))

    with pytest.raises(TypeError, match="times should be a list of lists"):
        spikes = Spikes(times=([2.3456, 7.89], [4.2812, 93.2]),
                        gids=spikegids,
                        types=spiketypes)

    with pytest.raises(TypeError, match="times should be a list of lists"):
        spikes = Spikes(times=[1, 2], gids=spikegids, types=spiketypes)

    with pytest.raises(ValueError,
                       match="times, gids, and types should be "
                       "lists of the same length"):
        spikes = Spikes(times=[[2.3456, 7.89]],
                        gids=spikegids,
                        types=spiketypes)

    with pytest.raises(TypeError,
                       match="spike_types should be str, "
                       "list, dict, or None"):
        spikes.plot_hist(spike_types=1, show=False)

    with pytest.raises(TypeError,
                       match=r"spike_types\[ev\] must be a list\. "
                       r"Got int\."):
        spikes.plot_hist(spike_types={'ev': 1}, show=False)

    with pytest.raises(ValueError,
                       match=r"Elements of spike_types must map to"
                       r" mutually exclusive input types\. L2_basket is found"
                       r" more than once\."):
        spikes.plot_hist(spike_types={'ev': ['L2_basket', 'L2_b']}, show=False)

    with pytest.raises(ValueError, match="No input types found for ABC"):
        spikes.plot_hist(spike_types='ABC', show=False)

    # Write spike file with no 'types' column
    # Check for gid_dict errors
    for fname in sorted(glob('/tmp/spk_*.txt')):
        times_gids_only = np.loadtxt(fname, dtype=str)[:, (0, 1)]
        np.savetxt(fname, times_gids_only, delimiter='\t', fmt='%s')
    with pytest.raises(ValueError,
                       match="gid_dict must be provided if spike "
                       "types are unspecified in the file /tmp/spk_0.txt"):
        spikes = read_spikes('/tmp/spk_*.txt')
    with pytest.raises(ValueError,
                       match="gid_dict should contain only "
                       "disjoint sets of gid values"):
        gid_dict = {
            'L2_pyramidal': range(3),
            'L2_basket': range(2, 4),
            'L5_pyramidal': range(4, 6),
            'L5_basket': range(6, 8)
        }
        spikes = read_spikes('/tmp/spk_*.txt', gid_dict=gid_dict)
Ejemplo n.º 7
0
def test_cell_response(tmpdir):
    """Test CellResponse object."""

    # Round-trip test
    spike_times = [[2.3456, 7.89], [4.2812, 93.2]]
    spike_gids = [[1, 3], [5, 7]]
    spike_types = [['L2_pyramidal', 'L2_basket'],
                   ['L5_pyramidal', 'L5_basket']]
    tstart, tstop = 0.1, 98.4
    gid_ranges = {
        'L2_pyramidal': range(1, 2),
        'L2_basket': range(3, 4),
        'L5_pyramidal': range(5, 6),
        'L5_basket': range(7, 8)
    }
    cell_response = CellResponse(spike_times=spike_times,
                                 spike_gids=spike_gids,
                                 spike_types=spike_types)
    cell_response.plot_spikes_hist(show=False)
    cell_response.write(tmpdir.join('spk_%d.txt'))
    assert cell_response == read_spikes(tmpdir.join('spk_*.txt'))

    assert ("CellResponse | 2 simulation trials" in repr(cell_response))

    with pytest.raises(TypeError,
                       match="spike_times should be a list of lists"):
        cell_response = CellResponse(spike_times=([2.3456,
                                                   7.89], [4.2812, 93.2]),
                                     spike_gids=spike_gids,
                                     spike_types=spike_types)

    with pytest.raises(TypeError,
                       match="spike_times should be a list of lists"):
        cell_response = CellResponse(spike_times=[1, 2],
                                     spike_gids=spike_gids,
                                     spike_types=spike_types)

    with pytest.raises(ValueError,
                       match="spike times, gids, and types should "
                       "be lists of the same length"):
        cell_response = CellResponse(spike_times=[[2.3456, 7.89]],
                                     spike_gids=spike_gids,
                                     spike_types=spike_types)

    cell_response = CellResponse(spike_times=spike_times,
                                 spike_gids=spike_gids,
                                 spike_types=spike_types)

    with pytest.raises(TypeError,
                       match="indices must be int, slice, or "
                       "array-like, not str"):
        cell_response['1']

    with pytest.raises(TypeError,
                       match="indices must be int, slice, or "
                       "array-like, not float"):
        cell_response[1.0]

    with pytest.raises(ValueError, match="ndarray cannot exceed 1 dimension"):
        cell_response[np.array([[1, 2], [3, 4]])]

    with pytest.raises(TypeError,
                       match="gids must be of dtype int, "
                       "not float64"):
        cell_response[np.array([1, 2, 3.0])]

    with pytest.raises(TypeError,
                       match="gids must be of dtype int, "
                       "not float64"):
        cell_response[[0, 1, 2, 2.0]]

    with pytest.raises(TypeError,
                       match="spike_types should be str, "
                       "list, dict, or None"):
        cell_response.plot_spikes_hist(spike_types=1, show=False)

    with pytest.raises(TypeError,
                       match=r"spike_types\[ev\] must be a list\. "
                       r"Got int\."):
        cell_response.plot_spikes_hist(spike_types={'ev': 1}, show=False)

    with pytest.raises(ValueError,
                       match=r"Elements of spike_types must map to"
                       r" mutually exclusive input types\. L2_basket is found"
                       r" more than once\."):
        cell_response.plot_spikes_hist(
            spike_types={'ev': ['L2_basket', 'L2_b']}, show=False)

    with pytest.raises(ValueError, match="No input types found for ABC"):
        cell_response.plot_spikes_hist(spike_types='ABC', show=False)

    with pytest.raises(ValueError,
                       match="tstart and tstop must be of type "
                       "int or float"):
        cell_response.mean_rates(tstart=0.1,
                                 tstop='ABC',
                                 gid_ranges=gid_ranges)

    with pytest.raises(ValueError, match="tstop must be greater than tstart"):
        cell_response.mean_rates(tstart=0.1, tstop=-1.0, gid_ranges=gid_ranges)

    with pytest.raises(ValueError,
                       match="Invalid mean_type. Valid "
                       "arguments include 'all', 'trial', or 'cell'."):
        cell_response.mean_rates(tstart=tstart,
                                 tstop=tstop,
                                 gid_ranges=gid_ranges,
                                 mean_type='ABC')

    test_rate = (1 / (tstop - tstart)) * 1000

    assert cell_response.mean_rates(tstart, tstop, gid_ranges) == {
        'L5_pyramidal': test_rate / 2,
        'L5_basket': test_rate / 2,
        'L2_pyramidal': test_rate / 2,
        'L2_basket': test_rate / 2
    }
    assert cell_response.mean_rates(tstart,
                                    tstop,
                                    gid_ranges,
                                    mean_type='trial') == {
                                        'L5_pyramidal': [0.0, test_rate],
                                        'L5_basket': [0.0, test_rate],
                                        'L2_pyramidal': [test_rate, 0.0],
                                        'L2_basket': [test_rate, 0.0]
                                    }
    assert cell_response.mean_rates(tstart,
                                    tstop,
                                    gid_ranges,
                                    mean_type='cell') == {
                                        'L5_pyramidal': [[0.0], [test_rate]],
                                        'L5_basket': [[0.0], [test_rate]],
                                        'L2_pyramidal': [[test_rate], [0.0]],
                                        'L2_basket': [[test_rate], [0.0]]
                                    }

    # Write spike file with no 'types' column
    # Check for gid_ranges errors
    for fname in sorted(glob(str(tmpdir.join('spk_*.txt')))):
        times_gids_only = np.loadtxt(fname, dtype=str)[:, (0, 1)]
        np.savetxt(fname, times_gids_only, delimiter='\t', fmt='%s')
    with pytest.raises(ValueError,
                       match="gid_ranges must be provided if "
                       "spike types are unspecified in the file "):
        cell_response = read_spikes(tmpdir.join('spk_*.txt'))
    with pytest.raises(ValueError,
                       match="gid_ranges should contain only "
                       "disjoint sets of gid values"):
        gid_ranges = {
            'L2_pyramidal': range(3),
            'L2_basket': range(2, 4),
            'L5_pyramidal': range(4, 6),
            'L5_basket': range(6, 8)
        }
        cell_response = read_spikes(tmpdir.join('spk_*.txt'),
                                    gid_ranges=gid_ranges)