def run_hnn_core(backend=None, n_jobs=1):
    """Test to check if hnn-core does not break."""
    # small snippet of data on data branch for now. To be deleted
    # later. Data branch should have only commit so it does not
    # pollute the history.
    data_url = ('https://raw.githubusercontent.com/jonescompneurolab/'
                'hnn-core/test_data/dpl.txt')
    if not op.exists('dpl.txt'):
        _fetch_file(data_url, 'dpl.txt')
    dpl_master = loadtxt('dpl.txt')

    hnn_core_root = op.dirname(hnn_core.__file__)

    # default params
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)

    # run the simulation
    net = Network(params)

    if backend == 'mpi':
        with MPIBackend(n_procs=2, mpi_cmd='mpiexec'):
            dpl = simulate_dipole(net)[0]
    elif backend == 'joblib':
        with JoblibBackend(n_jobs=n_jobs):
            dpl = simulate_dipole(net)[0]
    else:
        dpl = simulate_dipole(net)[0]

    # write the dipole to a file and compare
    fname = './dpl2.txt'
    dpl.write(fname)

    dpl_pr = loadtxt(fname)
    assert_array_equal(dpl_pr[:, 2], dpl_master[:, 2])  # L2
    assert_array_equal(dpl_pr[:, 3], dpl_master[:, 3])  # L5

    # Test spike type counts
    spiketype_counts = {}
    for spikegid in net.spikes.gids[0]:
        if net.gid_to_type(spikegid) not in spiketype_counts:
            spiketype_counts[net.gid_to_type(spikegid)] = 0
        else:
            spiketype_counts[net.gid_to_type(spikegid)] += 1
    assert 'common' not in spiketype_counts
    assert 'exgauss' not in spiketype_counts
    assert 'extpois' not in spiketype_counts
    assert spiketype_counts == {
        'evprox1': 269,
        'L2_basket': 54,
        'L2_pyramidal': 113,
        'L5_pyramidal': 395,
        'L5_basket': 85,
        'evdist1': 234,
        'evprox2': 269
    }
    def __call__(self, new_param_values):
        new_params = dict(
            zip(self.param_names,
                new_param_values.detach().cpu().numpy()))
        self.params.update(new_params)

        net = Network(self.params)
        with JoblibBackend(n_jobs=1):
            dpl = simulate_dipole(net, n_trials=1)

        summstats = torch.as_tensor(dpl[0].data['agg'])
        return summstats
Exemple #3
0
    def _run_hnn_core_fixture(backend=None,
                              n_procs=None,
                              n_jobs=1,
                              reduced=False,
                              record_vsoma=False,
                              record_isoma=False,
                              postproc=True):
        hnn_core_root = op.dirname(hnn_core.__file__)

        # default params
        params_fname = op.join(hnn_core_root, 'param', 'default.json')
        params = read_params(params_fname)

        if reduced:
            params.update({
                'N_pyr_x': 3,
                'N_pyr_y': 3,
                'tstop': 25,
                't_evprox_1': 5,
                't_evdist_1': 10,
                't_evprox_2': 20,
                'N_trials': 2
            })
        net = Network(params)

        # number of trials simulated
        assert all(
            len(src_feed_times) == params['N_trials']
            for src_type, src_feed_times in net.feed_times.items()
            if src_type != 'tonic')
        if backend == 'mpi':
            with MPIBackend(n_procs=n_procs, mpi_cmd='mpiexec'):
                dpls = simulate_dipole(net,
                                       record_vsoma=record_isoma,
                                       record_isoma=record_vsoma,
                                       postproc=postproc)
        elif backend == 'joblib':
            with JoblibBackend(n_jobs=n_jobs):
                dpls = simulate_dipole(net,
                                       record_vsoma=record_isoma,
                                       record_isoma=record_vsoma,
                                       postproc=postproc)
        else:
            dpls = simulate_dipole(net,
                                   record_vsoma=record_isoma,
                                   record_isoma=record_vsoma,
                                   postproc=postproc)

        return dpls, net
Exemple #4
0
    def __call__(self, new_param_values):
        new_params = dict(
            zip(self.param_names,
                new_param_values.detach().cpu().numpy()))
        self.params.update(new_params)

        net = Network(self.params)
        with JoblibBackend(n_jobs=1):
            dpl = simulate_dipole(net, n_trials=1)

        summstats = dpl[0].data['agg']
        spike_times = net.cell_response.spike_times
        spike_gids = net.cell_response.spike_gids
        spike_types = net.cell_response.spike_types
        return summstats, spike_times, spike_gids, spike_types
Exemple #5
0
    def _run_hnn_core_fixture(backend=None,
                              n_procs=None,
                              n_jobs=1,
                              reduced=False,
                              record_vsoma=False,
                              record_isoma=False,
                              postproc=True):
        hnn_core_root = op.dirname(hnn_core.__file__)

        # default params
        params_fname = op.join(hnn_core_root, 'param', 'default.json')
        params = read_params(params_fname)

        if reduced:
            params.update({
                'N_pyr_x': 3,
                'N_pyr_y': 3,
                'tstop': 40,
                't_evprox_1': 5,
                't_evdist_1': 10,
                't_evprox_2': 20,
                'N_trials': 2
            })
        net = Network(params, add_drives_from_params=True)

        # number of trials simulated
        for drive in net.external_drives.values():
            assert len(drive['events']) == params['N_trials']

        if backend == 'mpi':
            with MPIBackend(n_procs=n_procs, mpi_cmd='mpiexec'):
                dpls = simulate_dipole(net,
                                       record_vsoma=record_isoma,
                                       record_isoma=record_vsoma,
                                       postproc=postproc)
        elif backend == 'joblib':
            with JoblibBackend(n_jobs=n_jobs):
                dpls = simulate_dipole(net,
                                       record_vsoma=record_isoma,
                                       record_isoma=record_vsoma,
                                       postproc=postproc)
        else:
            dpls = simulate_dipole(net,
                                   record_vsoma=record_isoma,
                                   record_isoma=record_vsoma,
                                   postproc=postproc)

        return dpls, net
Exemple #6
0
    def _run_hnn_core_fixture(backend=None, n_procs=None, n_jobs=1,
                              reduced=False, record_vsoma=False,
                              record_isoma=False, postproc=False,
                              electrode_array=None):
        hnn_core_root = op.dirname(hnn_core.__file__)

        # default params
        params_fname = op.join(hnn_core_root, 'param', 'default.json')
        params = read_params(params_fname)

        tstop = 170.
        if reduced:
            params.update({'N_pyr_x': 3,
                           'N_pyr_y': 3,
                           't_evprox_1': 5,
                           't_evdist_1': 10,
                           't_evprox_2': 20,
                           'N_trials': 2})
            tstop = 40.
        net = jones_2009_model(params, add_drives_from_params=True)
        if electrode_array is not None:
            for name, positions in electrode_array.items():
                net.add_electrode_array(name, positions)

        if backend == 'mpi':
            with MPIBackend(n_procs=n_procs, mpi_cmd='mpiexec'):
                dpls = simulate_dipole(net, record_vsoma=record_isoma,
                                       record_isoma=record_vsoma,
                                       postproc=postproc, tstop=tstop)
        elif backend == 'joblib':
            with JoblibBackend(n_jobs=n_jobs):
                dpls = simulate_dipole(net, record_vsoma=record_isoma,
                                       record_isoma=record_vsoma,
                                       postproc=postproc, tstop=tstop)
        else:
            dpls = simulate_dipole(net, record_vsoma=record_isoma,
                                   record_isoma=record_vsoma,
                                   postproc=postproc, tstop=tstop)

        # check that the network object is picklable after the simulation
        pickle.dumps(net)

        # number of trials simulated
        for drive in net.external_drives.values():
            assert len(drive['events']) == params['N_trials']

        return dpls, net
                     numspikes=1,
                     location='distal',
                     n_drive_cells=1,
                     cell_specific=False,
                     weights_ampa=weights_ampa_d,
                     weights_nmda=weights_nmda_d,
                     synaptic_delays=synaptic_delays_d,
                     event_seed=2)

###############################################################################
# Now we run the simulation over 2 trials so that we can plot the average
# aggregate dipole. For a better match to the empirical waveform, set
# ``n_trials`` to be >=25.
n_trials = 2
# n_trials = 25
with JoblibBackend(n_jobs=2):
    dpls = simulate_dipole(net, tstop=170., n_trials=n_trials)

###############################################################################
# Since the model is a reduced representation of the larger network
# contributing to the response, the model response is noisier than it would be
# in the net activity from a larger network where these effects are averaged
# out, and the dipole amplitude is smaller than the recorded data. The
# post-processing steps of smoothing and scaling the simulated dipole response
# allow us to more accurately approximate the true signal responsible for the
# recorded macroscopic evoked response [1]_, [2]_.
dpl_smooth_win = 20
dpl_scalefctr = 12
for dpl in dpls:
    dpl.smooth(dpl_smooth_win)
    dpl.scale(dpl_scalefctr)
# This is a lot of parameters! We can also filter the
# parameters using unix-style wildcard characters
print(params['L2Pyr_soma*'])

###############################################################################
# Let us first create our network from the params file and visualize the cells
# inside it.
net = Network(params)
net.plot_cells()

###############################################################################
# Now let's simulate the dipole, running 2 trials with the Joblib backend.
# To run them in parallel we could set n_jobs to equal the number of trials.
from hnn_core import JoblibBackend

with JoblibBackend(n_jobs=1):
    dpls = simulate_dipole(net, n_trials=2)

###############################################################################
# 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()