Example #1
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])
Example #2
0
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'])
def read_dipoles_over_range(parameterValues, plotOK):

    # Read simulations
    dpls = []
    for p in parameterValues:
        fname = op.join(dplPath, "{0:.5e}.txt".format(p))
        dpls.append(read_dipole(fname))

    return dpls
Example #4
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)
Example #5
0
def read_dipoles_over_range(parameterValues, plotOK):

    # Read simulations
    dpls = []
    for p in parameterValues:
        fname = op.join(dplPath, "{0:.5e}.txt".format(p))
        dpls.append(read_dipole(fname))

    if plotOK:
        # Plot the results for all parameter values
        dipAmp = []
        for dpl in dpls:
            dipAmp.append(dpl.dpl['agg'])
        dipAmp = np.asarray(dipAmp).T
        plt.plot(dpls[0].t, dipAmp)
        plt.xlim(50, 700)
        plt.ylim(-500, 500)
        plt.xlabel('Time [ms]')
        plt.ylabel('Dipole Strength [nAm]')
        plt.legend(parameterValues)
        plt.show()

    return dpls
Example #6
0
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.arange(0, 6000 * params['dt'], params['dt'])
    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()

    # test smoothing and scaling
    dipole_raw = dipole.copy()
    dipole.scale(params['dipole_scalefctr'])
    dipole.smooth(window_len=params['dipole_smooth_win'])
    with pytest.raises(AssertionError):
        assert_allclose(dipole.data['agg'], dipole_raw.data['agg'])
    assert_allclose(
        dipole.data['agg'],
        (params['dipole_scalefctr'] *
         dipole_raw.smooth(params['dipole_smooth_win']).data['agg']))

    dipole.plot(show=False)
    plot_dipole([dipole, dipole], show=False)

    # Test IO
    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])

    # average an n_of_1 dipole list
    single_dpl_avg = average_dipoles([dipole])
    for dpl_key in single_dpl_avg.data.keys():
        assert_allclose(dipole_read.data[dpl_key],
                        single_dpl_avg.data[dpl_key],
                        rtol=0,
                        atol=0.000051)

    # average dipole list with one dipole object and a zero dipole object
    n_times = len(dipole_read.data['agg'])
    dpl_null = Dipole(np.zeros(n_times, ), np.zeros((n_times, 3)))
    dpl_1 = [dipole, dpl_null]
    dpl_avg = average_dipoles(dpl_1)
    for dpl_key in dpl_avg.data.keys():
        assert_allclose(dpl_1[0].data[dpl_key] / 2., dpl_avg.data[dpl_key])

    # Test experimental dipole
    dipole_exp = Dipole(times, data[:, 1])
    dipole_exp.write(dpl_out_fname)
    dipole_exp_read = read_dipole(dpl_out_fname)
    assert_allclose(dipole_exp.data['agg'],
                    dipole_exp_read.data['agg'],
                    rtol=1e-2)
    dipole_exp_avg = average_dipoles([dipole_exp, dipole_exp])
    assert_allclose(dipole_exp.data['agg'], dipole_exp_avg.data['agg'])

    # XXX all below to be deprecated in 0.3
    dpls_raw, net = run_hnn_core_fixture(backend='joblib',
                                         n_jobs=1,
                                         reduced=True,
                                         record_isoma=True,
                                         record_vsoma=True)
    # test deprecation of postproc
    with pytest.warns(DeprecationWarning,
                      match='The postproc-argument is deprecated'):
        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['dipole_smooth_win'],
                           net._params['dipole_scalefctr'])
    assert_allclose(dpls_raw[0].data['agg'], dpls[0].data['agg'])
Example #7
0
# The number of cores may need modifying depending on your current machine.
n_procs = 10

###############################################################################
# First, we will load experimental data into Dipole object.
#
# This is a different experiment than the one to which the base parameters were
# tuned. So, the initial RMSE will be large, giving the optimization procedure
# a lot to work with.
from urllib.request import urlretrieve

data_url = ('https://raw.githubusercontent.com/jonescompneurolab/hnn/master/'
            'data/MEG_detection_data/S1_SupraT.txt')
urlretrieve(data_url, 'S1_SupraT.txt')
exp_dpl = read_dipole('S1_SupraT.txt')

###############################################################################
# Read the base parameters from a file
params_fname = op.join(hnn_core_root, 'param', 'default.json')
params = read_params(params_fname)

###############################################################################
# Let's first simulate the dipole with some initial parameters. The parameter
# definitions also contain the drives. Even though we could add drives
# explicitly through our API
# (see :ref:`sphx_glr_auto_examples_workflows_plot_simulate_evoked.py`),
# for conciseness,
# we add them automatically from the parameter files

scale_factor = 3000.