コード例 #1
0
def test_legacy_params():
    """Test reading legacy .param file."""
    param_url = ('https://raw.githubusercontent.com/hnnsolver/'
                 'hnn-core/test_data/default.param')
    params_legacy_fname = op.join(hnn_core_root, 'param', 'default.param')
    if not op.exists(params_legacy_fname):
        _fetch_file(param_url, params_legacy_fname)

    params_new_fname = op.join(hnn_core_root, 'param', 'default.json')
    params_legacy = read_params(params_legacy_fname)
    params_new = read_params(params_new_fname)

    assert params_new == params_legacy
コード例 #2
0
def calcium_model(params=None, add_drives_from_params=False):
    """Instantiate the Jones 2009 model with improved calcium dynamics.

    Returns
    -------
    net : Instance of Network object
        Network object used to store the Jones 2009 model with an impoved
        calcium channel distribution.

    See Also
    --------
    jones_2009_model

    Notes
    -----
    This model builds on the Jones 2009 model by using a more biologically
    accurate distribution of calcium channels on L5 pyramidal cells.
    Specifically, this model introduces a distance dependent maximum
    conductance (gbar) on calcium channels such that the gbar linearly
    decreases along the dendrites in the direction of the soma.
    """
    hnn_core_root = op.dirname(hnn_core.__file__)
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    if params is None:
        params = read_params(params_fname)

    net = jones_2009_model(params, add_drives_from_params)

    # Replace L5 pyramidal cell template with updated calcium
    cell_name = 'L5_pyramidal'
    pos = net.cell_types[cell_name].pos
    net.cell_types[cell_name] = pyramidal_ca(
        cell_name=_short_name(cell_name), pos=pos)

    return net
コード例 #3
0
ファイル: test_network.py プロジェクト: ntolley/hnn-core
def test_add_cell_type():
    """Test adding a new cell type."""
    params = read_params(params_fname)
    net = jones_2009_model(params)
    # instantiate drive events for NetworkBuilder
    net._instantiate_drives(tstop=params['tstop'], n_trials=params['N_trials'])

    n_total_cells = net._n_cells
    pos = [(0, idx, 0) for idx in range(10)]
    tau1 = 0.6

    new_cell = net.cell_types['L2_basket'].copy()
    net._add_cell_type('new_type', pos=pos, cell_template=new_cell)
    net.cell_types['new_type'].synapses['gabaa']['tau1'] = tau1

    n_new_type = len(net.gid_ranges['new_type'])
    assert n_new_type == len(pos)
    net.add_connection('L2_basket',
                       'new_type',
                       loc='proximal',
                       receptor='gabaa',
                       weight=8e-3,
                       delay=1,
                       lamtha=2)

    network_builder = NetworkBuilder(net)
    assert net._n_cells == n_total_cells + len(pos)
    n_basket = len(net.gid_ranges['L2_basket'])
    n_connections = n_basket * n_new_type
    assert len(network_builder.ncs['L2Basket_new_type_gabaa']) == n_connections
    nc = network_builder.ncs['L2Basket_new_type_gabaa'][0]
    assert nc.syn().tau1 == tau1
コード例 #4
0
def test_hnn_core():
    """Test to check if MNE neuron 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.join(op.dirname(hnn_core.__file__), '..')

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

    net = Network(params, n_jobs=1)
    dpl = simulate_dipole(net)[0]

    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
コード例 #5
0
def test_str_to_net():
    """Test reading the network via a string"""

    hnn_core_root = op.dirname(hnn_core.__file__)

    # prepare network
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)
    net = Network(params, add_drives_from_params=True)

    pickled_net = _pickle_data(net)

    input_str = '@start_of_net@' + pickled_net.decode() + \
        '@end_of_net:%d@\n' % (len(pickled_net))

    received_net = _str_to_net(input_str)
    assert isinstance(received_net, Network)

    # muck with the data size in the signal
    input_str = '@start_of_net@' + pickled_net.decode() + \
        '@end_of_net:%d@\n' % (len(pickled_net) + 1)

    expected_string = "Got incorrect network size: %d bytes " % \
        len(pickled_net) + "expected length: %d" % \
        (len(pickled_net) + 1)

    # process input from queue
    with pytest.raises(ValueError, match=expected_string):
        _str_to_net(input_str)
コード例 #6
0
ファイル: test_feed.py プロジェクト: tbardouille/hnn-core
def test_external_common_feeds():
    """Test external common feeds to proximal and distal dendrites."""
    hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)

    # default parameters have no common inputs (distal or proximal),
    params.update({'input_dist_A_weight_L2Pyr_ampa': 5.4e-5,
                   'input_dist_A_weight_L5Pyr_ampa': 5.4e-5,
                   't0_input_dist': 50,
                   'input_prox_A_weight_L2Pyr_ampa': 5.4e-5,
                   'input_prox_A_weight_L5Pyr_ampa': 5.4e-5,
                   't0_input_prox': 50})

    with Network(deepcopy(params)) as net:
        net._create_all_spike_sources()

        assert len(net.common_feeds) == 2  # (distal & proximal)
        for ei in net.common_feeds:
            assert ei.feed_type == 'common'
            assert ei.cell_type is None  # artificial cell
            assert hasattr(ei, 'nrn_eventvec')
            assert hasattr(ei, 'nrn_vecstim')
            assert ei.nrn_eventvec.hname().startswith('Vector')
            assert hasattr(ei.nrn_vecstim, 'play')
            # parameters should lead to > 0 input spikes
            assert len(ei.nrn_eventvec.as_numpy()) > 0

            # check that ei.p_ext matches params
            loc = ei.params['loc'][:4]  # loc=prox or dist
            for layer in ['L2', 'L5']:
                key = 'input_{}_A_weight_{}Pyr_ampa'.format(loc, layer)
                assert ei.params[layer + 'Pyr_ampa'][0] == params[key]
コード例 #7
0
def test_split_by_evinput():
    """Test splitting evoked input."""
    hnn_core_root = op.dirname(hnn_core.__file__)
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)

    timing_range_multiplier = 3.0
    sigma_range_multiplier = 50.0
    synweight_range_multiplier = 500.0
    decay_multiplier = 1.6
    evinput_params = _split_by_evinput(params, sigma_range_multiplier,
                                       timing_range_multiplier,
                                       synweight_range_multiplier)
    assert list(evinput_params.keys()) == [
        'evprox_1', 'evdist_1', 'evprox_2']
    for evinput in evinput_params.values():
        assert list(evinput.keys()) == ['mean', 'sigma', 'ranges',
                                        'start', 'end']

    evinput_params = _generate_weights(evinput_params, params,
                                       decay_multiplier)
    for evinput in evinput_params.values():
        assert list(evinput.keys()) == ['ranges', 'start', 'end',
                                        'weights', 'opt_start',
                                        'opt_end']
コード例 #8
0
ファイル: qt_dialog.py プロジェクト: jonescompneurolab/hnn
    def __init__(self, parent, paramfn):
        super(BaseParamDialog, self).__init__(parent)
        self.proxparamwin = None
        self.distparamwin = None
        self.netparamwin = None
        self.syngainparamwin = None
        self.runparamwin = RunParamDialog(self, parent)
        self.cellparamwin = CellParamDialog(self)
        self.netparamwin = NetworkParamDialog(self)
        self.syngainparamwin = SynGainParamDialog(self, self.netparamwin)
        self.proxparamwin = OngoingInputParamDialog(self, 'Proximal')
        self.distparamwin = OngoingInputParamDialog(self, 'Distal')
        self.evparamwin = EvokedInputParamDialog(self, None)
        self.optparamwin = OptEvokedInputParamDialog(self, parent)
        self.poisparamwin = PoissonInputParamDialog(self, None)
        self.tonicparamwin = TonicInputParamDialog(self, None)
        self.lsubwin = [self.runparamwin, self.cellparamwin, self.netparamwin,
                        self.proxparamwin, self.distparamwin, self.evparamwin,
                        self.poisparamwin, self.tonicparamwin,
                        self.optparamwin]
        self.paramfn = paramfn
        self.parent = parent

        self.params = read_params(self.paramfn)
        self.initUI()  # requires self.params
        self.updateDispParam(self.params)
コード例 #9
0
def test_dipole():
    """Test dipole object."""
    hnn_core_root = op.dirname(hnn_core.__file__)
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    dpl_out_fname = '/tmp/dpl1.txt'
    params = read_params(params_fname)
    times = np.random.random(6000)
    data = np.random.random((6000, 3))
    dipole = Dipole(times, data)
    dipole.baseline_renormalize(params)
    dipole.convert_fAm_to_nAm()
    dipole.scale(params['dipole_scalefctr'])
    dipole.smooth(params['dipole_smooth_win'] / params['dt'])
    dipole.plot(show=False)
    viz.plot_dipole([dipole, dipole], show=False)
    dipole.write(dpl_out_fname)
    dipole_read = read_dipole(dpl_out_fname)
    assert_allclose(dipole_read.times, dipole.times, rtol=0, atol=0.00051)
    for dpl_key in dipole.data.keys():
        assert_allclose(dipole_read.data[dpl_key],
                        dipole.data[dpl_key], rtol=0, atol=0.000051)

    # average two identical dipole objects
    dipole_avg = average_dipoles([dipole, dipole_read])
    for dpl_key in dipole_avg.data.keys():
        assert_allclose(dipole_read.data[dpl_key],
                        dipole_avg.data[dpl_key], rtol=0, atol=0.000051)

    with pytest.raises(ValueError, match="Dipole at index 0 was already an "
                       "average of 2 trials"):
        dipole_avg = average_dipoles([dipole_avg, dipole_read])
コード例 #10
0
ファイル: test_cell.py プロジェクト: tbardouille/hnn-core
def test_dipole():
    """Test params object."""
    hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)

    with Network(params) as net:
        net.build()
        net.cells[0].plot_voltage()
コード例 #11
0
ファイル: test_cell.py プロジェクト: plcrodrigues/hnn-core
def test_cell():
    """Test cells object."""
    hnn_core_root = op.dirname(hnn_core.__file__)
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)

    net = Network(params)
    with NeuronNetwork(net) as neuron_net:
        neuron_net.cells[0].plot_voltage()
コード例 #12
0
    def __init__(self, params_fname, prior_dict):
        if 'DISPLAY' in os.environ:
            del os.environ['DISPLAY']

        import hnn_core
        from hnn_core import simulate_dipole, Network, read_params, JoblibBackend, MPIBackend
        self.params = read_params(params_fname)
        #self.params['tstop'] = 100
        self.param_names = list(prior_dict.keys())
コード例 #13
0
ファイル: test_viz.py プロジェクト: vinven7/hnn-core
def test_network_visualization():
    """Test network visualisations."""
    hnn_core_root = op.dirname(hnn_core.__file__)
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)
    params.update({'N_pyr_x': 3,
                   'N_pyr_y': 3})
    net = Network(params)
    plot_cells(net)
コード例 #14
0
ファイル: test_dipole.py プロジェクト: samikane/hnn-core
def test_dipole(tmpdir, run_hnn_core_fixture):
    """Test dipole object."""
    hnn_core_root = op.dirname(hnn_core.__file__)
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    dpl_out_fname = tmpdir.join('dpl1.txt')
    params = read_params(params_fname)
    times = np.random.random(6000)
    data = np.random.random((6000, 3))
    dipole = Dipole(times, data)
    dipole.baseline_renormalize(params['N_pyr_x'], params['N_pyr_y'])
    dipole.convert_fAm_to_nAm()
    dipole.scale(params['dipole_scalefctr'])
    dipole.smooth(params['dipole_smooth_win'] / params['dt'])
    dipole.plot(show=False)
    plot_dipole([dipole, dipole], show=False)
    dipole.write(dpl_out_fname)
    dipole_read = read_dipole(dpl_out_fname)
    assert_allclose(dipole_read.times, dipole.times, rtol=0, atol=0.00051)
    for dpl_key in dipole.data.keys():
        assert_allclose(dipole_read.data[dpl_key],
                        dipole.data[dpl_key],
                        rtol=0,
                        atol=0.000051)

    # average two identical dipole objects
    dipole_avg = average_dipoles([dipole, dipole_read])
    for dpl_key in dipole_avg.data.keys():
        assert_allclose(dipole_read.data[dpl_key],
                        dipole_avg.data[dpl_key],
                        rtol=0,
                        atol=0.000051)

    with pytest.raises(ValueError,
                       match="Dipole at index 0 was already an "
                       "average of 2 trials"):
        dipole_avg = average_dipoles([dipole_avg, dipole_read])

    # test postproc
    dpls_raw, net = run_hnn_core_fixture(backend='joblib',
                                         n_jobs=1,
                                         reduced=True,
                                         record_isoma=True,
                                         record_vsoma=True,
                                         postproc=False)
    dpls, _ = run_hnn_core_fixture(backend='joblib',
                                   n_jobs=1,
                                   reduced=True,
                                   record_isoma=True,
                                   record_vsoma=True,
                                   postproc=True)
    with pytest.raises(AssertionError):
        assert_allclose(dpls[0].data['agg'], dpls_raw[0].data['agg'])

    dpls_raw[0].post_proc(net.params['N_pyr_x'], net.params['N_pyr_y'],
                          net.params['dipole_smooth_win'] / net.params['dt'],
                          net.params['dipole_scalefctr'])
    assert_allclose(dpls_raw[0].data['agg'], dpls[0].data['agg'])
コード例 #15
0
def test_read_legacy_params():
    """Test reading of legacy .param file."""
    param_url = ('https://raw.githubusercontent.com/hnnsolver/'
                 'hnn-core/test_data/default.param')
    params_legacy_fname = op.join(hnn_core_root, 'param', 'default.param')
    if not op.exists(params_legacy_fname):
        urlretrieve(param_url, params_legacy_fname)

    params_new_fname = op.join(hnn_core_root, 'param', 'default.json')
    params_legacy = read_params(params_legacy_fname)
    params_new = read_params(params_new_fname)

    params_new_seedless = {key: val for key, val in params_new.items()
                           if key not in params_new['prng_seedcore*'].keys()}
    params_legacy_seedless = {key: val for key, val in params_legacy.items()
                              if key not in
                              params_legacy['prng_seedcore*'].keys()}
    assert params_new_seedless == params_legacy_seedless
コード例 #16
0
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
    }
コード例 #17
0
def test_network():
    """Test network object."""
    hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)
    net = Network(deepcopy(params))
    for p in params:
        assert params[p] == net.params[p]
    assert len(params) == len(net.params)
    print(net)
    print(net.cells[:2])
コード例 #18
0
ファイル: test_params.py プロジェクト: tbardouille/hnn-core
def test_base_params():
    """Test default params object matches base params"""
    param_url = ('https://raw.githubusercontent.com/jonescompneurolab/'
                 'hnn-core/test_data/base.json')
    params_base_fname = op.join(hnn_core_root, 'param', 'base.json')
    if not op.exists(params_base_fname):
        _fetch_file(param_url, params_base_fname)

    params_base = read_params(params_base_fname)
    params = Params()
    assert params == params_base
コード例 #19
0
def test_tonic_biases():
    """Test tonic biases."""
    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)

    net = hnn_core.Network(params, add_drives_from_params=True)
    with pytest.raises(ValueError, match=r'cell_type must be one of .*$'):
        net.add_tonic_bias(cell_type='name_nonexistent', amplitude=1.0,
                           t0=0.0, T=4.0)

    with pytest.raises(ValueError, match='Duration of tonic input cannot be'
                       ' negative'):
        net.add_tonic_bias(cell_type='L2_pyramidal', amplitude=1.0,
                           t0=5.0, T=4.0)

    with pytest.raises(ValueError, match='End time of tonic input cannot be'
                       ' negative'):
        net.add_tonic_bias(cell_type='L2_pyramidal', amplitude=1.0,
                           t0=5.0, T=-1.)

    with pytest.raises(ValueError, match='parameter may be missing'):
        params['Itonic_T_L2Pyr_soma'] = 5.0
        net = hnn_core.Network(params, add_drives_from_params=True)

    params.update({
        'N_pyr_x': 3, 'N_pyr_y': 3,
        'tstop': 25, 'N_trials': 1,
        'dipole_smooth_win': 5,
        't_evprox_1': 5,
        't_evdist_1': 10,
        't_evprox_2': 20,
        # tonic inputs
        'Itonic_A_L2Pyr_soma': 1.0,
        'Itonic_t0_L2Pyr_soma': 5.0,
        'Itonic_T_L2Pyr_soma': 15.0
    })
    # old API
    net = hnn_core.Network(params, add_drives_from_params=True)
    assert 'tonic' in net.external_biases
    assert 'L2_pyramidal' in net.external_biases['tonic']

    # new API
    net = hnn_core.Network(params)
    net.add_tonic_bias(cell_type='L2_pyramidal', amplitude=1.0)
    assert 'tonic' in net.external_biases
    assert 'L5_pyramidal' not in net.external_biases['tonic']
    assert net.external_biases['tonic']['L2_pyramidal']['t0'] == 0
    assert net.external_biases[
        'tonic']['L2_pyramidal']['T'] == net.params['tstop']
    with pytest.raises(ValueError, match=r'Tonic bias already defined for.*$'):
        net.add_tonic_bias(cell_type='L2_pyramidal', amplitude=1.0)
コード例 #20
0
ファイル: test_viz.py プロジェクト: rythorpe/hnn-core
def test_network_visualization():
    """Test network visualisations."""
    hnn_core_root = op.dirname(hnn_core.__file__)
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)
    params.update({'N_pyr_x': 3,
                   'N_pyr_y': 3})
    net = jones_2009_model(params)
    plot_cells(net)
    ax = net.cell_types['L2_pyramidal'].plot_morphology()
    assert len(ax.lines) == 8

    conn_idx = 0
    plot_connectivity_matrix(net, conn_idx, show=False)
    with pytest.raises(TypeError, match='net must be an instance of'):
        plot_connectivity_matrix('blah', conn_idx, show_weight=False)

    with pytest.raises(TypeError, match='conn_idx must be an instance of'):
        plot_connectivity_matrix(net, 'blah', show_weight=False)

    with pytest.raises(TypeError, match='show_weight must be an instance of'):
        plot_connectivity_matrix(net, conn_idx, show_weight='blah')

    src_gid = 5
    plot_cell_connectivity(net, conn_idx, src_gid, show=False)
    with pytest.raises(TypeError, match='net must be an instance of'):
        plot_cell_connectivity('blah', conn_idx, src_gid=src_gid)

    with pytest.raises(TypeError, match='conn_idx must be an instance of'):
        plot_cell_connectivity(net, 'blah', src_gid)

    with pytest.raises(TypeError, match='src_gid must be an instance of'):
        plot_cell_connectivity(net, conn_idx, src_gid='blah')

    with pytest.raises(ValueError, match='src_gid -1 not a valid cell ID'):
        plot_cell_connectivity(net, conn_idx, src_gid=-1)

    # test interactive clicking updates the position of src_cell in plot
    del net.connectivity[-1]
    conn_idx = 15
    net.add_connection(net.gid_ranges['L2_pyramidal'][::2],
                       'L5_basket', 'soma',
                       'ampa', 0.00025, 1.0, lamtha=3.0,
                       probability=0.8)
    fig = plot_cell_connectivity(net, conn_idx)
    ax_src, ax_target, _ = fig.axes

    pos = net.pos_dict['L2_pyramidal'][2]
    _fake_click(fig, ax_src, [pos[0], pos[1]])
    pos_in_plot = ax_target.collections[2].get_offsets().data[0]
    assert_allclose(pos[:2], pos_in_plot)
コード例 #21
0
    def onActivateSimCB(self, paramfn):
        """load simulation when activating simulation combobox"""

        if paramfn != self.baseparamwin.paramfn:
            try:
                params = read_params(paramfn)
            except ValueError:
                QMessageBox.information(
                    self, "HNN", "WARNING: could not"
                    "retrieve parameters from %s" % paramfn)
                return
            self.baseparamwin.paramfn = paramfn

            self.updateDatCanv(params)
コード例 #22
0
def test_network_visualization():
    """Test network visualisations."""
    hnn_core_root = op.dirname(hnn_core.__file__)
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)
    params.update({'N_pyr_x': 3,
                   'N_pyr_y': 3})
    net = Network(params)
    plot_cells(net)
    with pytest.raises(ValueError, match='Unrecognized cell type'):
        plot_cell_morphology(cell_types='blah')
    axes = plot_cell_morphology(cell_types='L2Pyr')
    assert len(axes) == 1
    assert len(axes[0].lines) == 8
コード例 #23
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
コード例 #24
0
    def selParamFileDialog(self):
        """bring up window to select simulation parameter file"""

        relative_root_path = os.path.join(os.path.dirname(__file__), '..')
        hnn_root_dir = os.path.realpath(relative_root_path)

        qfd = QFileDialog()
        qfd.setHistory([
            os.path.join(get_output_dir(), 'param'),
            os.path.join(hnn_root_dir, 'param')
        ])
        fn = qfd.getOpenFileName(self, 'Open param file',
                                 os.path.join(hnn_root_dir, 'param'),
                                 "Param files (*.param)")
        if len(fn) > 0 and fn[0] == '':
            # no file selected in dialog
            return

        tmpfn = os.path.abspath(fn[0])

        try:
            params = read_params(tmpfn)
        except ValueError:
            QMessageBox.information(
                self, "HNN", "WARNING: could not"
                "retrieve parameters from %s" % tmpfn)
            return

        # check that valid number of trials was given
        if 'N_trials' not in params or params['N_trials'] == 0:
            print("Warning: invalid configured number of trials."
                  " Setting 'N_trials' to 1.")
            params['N_trials'] = 1

        # Now update GUI components
        self.baseparamwin.paramfn = tmpfn

        # now update the GUI components to reflect the param file selected
        self.baseparamwin.updateDispParam(params)
        self.setWindowTitle(self.baseparamwin.paramfn)

        self.initSimCanvas()  # recreate canvas

        # check if param file exists in combo box already
        cb_index = self.cbsim.findText(self.baseparamwin.paramfn)
        self.populateSimCB(cb_index)  # populate the combobox

        if self.sim_data.get_exp_data_size() > 0:
            self.toggleEnableOptimization(True)
コード例 #25
0
ファイル: test_dipole.py プロジェクト: jessfeld/hnn-core
def test_dipole():
    """Test params object."""
    hnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)

    times = np.random.random(6000)
    data = np.random.random((6000, 3))
    dipole = Dipole(times, data)
    dipole.baseline_renormalize(params)
    dipole.convert_fAm_to_nAm()
    dipole.scale(params['dipole_scalefctr'])
    dipole.smooth(params['dipole_smooth_win'] / params['dt'])
    dipole.plot(layer='agg')
    dipole.write('/tmp/dpl1.txt')
コード例 #26
0
ファイル: conftest.py プロジェクト: vinven7/hnn-core
    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
コード例 #27
0
    def updateSelectedSim(self, sim_idx):
        """Update the sim shown in the ComboBox"""

        paramfn = self.cbsim.itemText(sim_idx)
        try:
            params = read_params(paramfn)
        except ValueError:
            QMessageBox.information(
                self, "HNN", "WARNING: could not"
                "retrieve parameters from %s" % paramfn)
            return
        self.baseparamwin.paramfn = paramfn

        # update GUI
        self.updateDatCanv(params)
        self.cbsim.setCurrentIndex(sim_idx)
コード例 #28
0
ファイル: conftest.py プロジェクト: rythorpe/hnn-core
    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
コード例 #29
0
def test_dipole_visualization():
    """Test dipole visualisations."""
    hnn_core_root = op.dirname(hnn_core.__file__)
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)
    params.update({'N_pyr_x': 3,
                   'N_pyr_y': 3,
                   'tstop': 100.})
    net = Network(params)
    weights_ampa_p = {'L2_pyramidal': 5.4e-5, 'L5_pyramidal': 5.4e-5}
    syn_delays_p = {'L2_pyramidal': 0.1, 'L5_pyramidal': 1.}

    net.add_bursty_drive(
        'beta_prox', tstart=0., burst_rate=25, burst_std=5,
        numspikes=1, spike_isi=0, repeats=11, location='proximal',
        weights_ampa=weights_ampa_p, synaptic_delays=syn_delays_p, seedcore=14)

    dpls = simulate_dipole(net, n_trials=2, postproc=False)
    fig = dpls[0].plot()  # plot the first dipole alone
    axes = fig.get_axes()[0]
    dpls[0].copy().smooth(window_len=10).plot(ax=axes)  # add smoothed versions
    dpls[0].copy().savgol_filter(h_freq=30).plot(ax=axes)  # on top

    # test decimation options
    plot_dipole(dpls[0], decim=2)
    for dec in [-1, [2, 2.]]:
        with pytest.raises(ValueError,
                           match='each decimation factor must be a positive'):
            plot_dipole(dpls[0], decim=dec)

    # test plotting multiple dipoles as overlay
    fig = plot_dipole(dpls)

    # multiple TFRs get averaged
    fig = plot_tfr_morlet(dpls, freqs=np.arange(23, 26, 1.), n_cycles=3)

    with pytest.raises(RuntimeError,
                       match="All dipoles must be scaled equally!"):
        plot_dipole([dpls[0].copy().scale(10), dpls[1].copy().scale(20)])
    with pytest.raises(RuntimeError,
                       match="All dipoles must be scaled equally!"):
        plot_psd([dpls[0].copy().scale(10), dpls[1].copy().scale(20)])
    with pytest.raises(RuntimeError,
                       match="All dipoles must be sampled equally!"):
        dpl_sfreq = dpls[0].copy()
        dpl_sfreq.sfreq /= 10
        plot_psd([dpls[0], dpl_sfreq])
コード例 #30
0
def test_read_params():
    """Test reading of params object."""
    params_fname = op.join(hnn_core_root, 'param', 'default.json')
    params = read_params(params_fname)
    print(params)
    print(params['L2Pyr*'])

    # unsupported extension
    pytest.raises(ValueError, read_params, 'params.txt')
    # empty file
    empty_fname = op.join(hnn_core_root, 'param', 'empty.json')
    with open(empty_fname, 'w') as json_data:
        json.dump({}, json_data)
    pytest.raises(ValueError, read_params, empty_fname)
    # non dict type
    pytest.raises(ValueError, Params, [])
    pytest.raises(ValueError, Params, 'sdfdfdf')