示例#1
0
def test_simulate_NIRS():

    raw = simulate_nirs_raw(sfreq=3.,
                            amplitude=1.,
                            sig_dur=300.,
                            stim_dur=5.,
                            isi_min=15.,
                            isi_max=45.)
    assert 'hbo' in raw
    assert raw.info['sfreq'] == 3.
    assert raw.get_data().shape == (1, 900)
    assert np.max(raw.get_data()) < 1.2 * 1.e-6
    assert raw.annotations.description[0] == 'A'
    assert raw.annotations.duration[0] == 5
    assert np.min(np.diff(raw.annotations.onset)) > 15. + 5.
    assert np.max(np.diff(raw.annotations.onset)) < 45. + 5.

    with pytest.raises(AssertionError, match='Same number of'):
        raw = simulate_nirs_raw(sfreq=3.,
                                amplitude=[1., 2.],
                                sig_dur=300.,
                                stim_dur=5.,
                                isi_min=15.,
                                isi_max=45.)

    raw = simulate_nirs_raw(sfreq=3.,
                            amplitude=[0., 2., 4.],
                            annot_desc=['Control', 'Cond_A', 'Cond_B'],
                            stim_dur=[5, 5, 5],
                            sig_dur=900.,
                            isi_min=15.,
                            isi_max=45.)
    design_matrix = make_first_level_design_matrix(raw,
                                                   stim_dur=5.0,
                                                   drift_order=1,
                                                   drift_model='polynomial')
    glm_est = run_GLM(raw, design_matrix)
    df = glm_to_tidy(raw, glm_est, design_matrix)
    df = _tidy_long_to_wide(df)

    assert df.query("condition in ['Control']")['theta'].values[0] == \
        pytest.approx(0)
    assert df.query("condition in ['Cond_A']")['theta'].values[0] == \
        pytest.approx(2e-6)
    assert df.query("condition in ['Cond_B']")['theta'].values[0] == \
        pytest.approx(4e-6)
示例#2
0
def test_run_GLM_order():
    raw = simulate_nirs_raw(sig_dur=200, stim_dur=5., sfreq=3)
    design_matrix = make_first_level_design_matrix(raw,
                                                   stim_dur=5.,
                                                   drift_order=1,
                                                   drift_model='polynomial')

    # Default should be first order AR
    glm_estimates = run_glm(raw, design_matrix)
    assert glm_estimates.pick("Simulated").model()[0].order == 1

    # Default should be first order AR
    glm_estimates = run_glm(raw, design_matrix, noise_model='ar2')
    assert glm_estimates.pick("Simulated").model()[0].order == 2

    glm_estimates = run_glm(raw, design_matrix, noise_model='ar7')
    assert glm_estimates.pick("Simulated").model()[0].order == 7

    # Auto should be 4 times sample rate
    cov = Covariance(np.ones(1) * 1e-11,
                     raw.ch_names,
                     raw.info['bads'],
                     raw.info['projs'],
                     nfree=0)
    raw = add_noise(raw, cov, iir_filter=iir_filter)
    glm_estimates = run_glm(raw, design_matrix, noise_model='auto')
    assert glm_estimates.pick("Simulated").model()[0].order == 3 * 4

    raw = simulate_nirs_raw(sig_dur=10, stim_dur=5., sfreq=2)
    cov = Covariance(np.ones(1) * 1e-11,
                     raw.ch_names,
                     raw.info['bads'],
                     raw.info['projs'],
                     nfree=0)
    raw = add_noise(raw, cov, iir_filter=iir_filter)
    design_matrix = make_first_level_design_matrix(raw,
                                                   stim_dur=5.,
                                                   drift_order=1,
                                                   drift_model='polynomial')
    # Auto should be 4 times sample rate
    glm_estimates = run_glm(raw, design_matrix, noise_model='auto')
    assert glm_estimates.pick("Simulated").model()[0].order == 2 * 4
def test_high_pass_helpers():
    # Test the helpers give reasonable values
    raw = simulate_nirs_raw(sfreq=1.,
                            amplitude=1.,
                            sig_dur=300.,
                            stim_dur=1.,
                            isi_min=20.,
                            isi_max=38.)
    lisi, names = longest_inter_annotation_interval(raw)
    lisi = lisi[0]
    assert lisi >= 20
    assert lisi <= 40
    assert drift_high_pass(raw) >= 1 / (40 * 2)
    assert drift_high_pass(raw) <= 1 / (20 * 2)
示例#4
0
def test_simulate_NIRS_single_channel():

    raw = simulate_nirs_raw(sfreq=3.,
                            amplitude=1.,
                            sig_dur=300.,
                            stim_dur=5.,
                            isi_min=15.,
                            isi_max=45.)
    assert 'hbo' in raw
    assert raw.info['sfreq'] == 3.
    assert raw.get_data().shape == (1, 900)
    assert np.max(raw.get_data()) < 1.2 * 1.e-6
    assert raw.annotations.description[0] == 'A'
    assert raw.annotations.duration[0] == 5
    assert np.min(np.diff(raw.annotations.onset)) > 15. + 5.
    assert np.max(np.diff(raw.annotations.onset)) < 45. + 5.

    with pytest.raises(AssertionError, match='Same number of'):
        _ = simulate_nirs_raw(sfreq=3.,
                              amplitude=[1., 2.],
                              sig_dur=300.,
                              stim_dur=5.,
                              isi_min=15.,
                              isi_max=45.)
示例#5
0
def test_simulate_NIRS():

    raw = simulate_nirs_raw(sfreq=3.,
                            amplitude=1.,
                            sig_dur=300.,
                            stim_dur=5.,
                            isi_min=15.,
                            isi_max=45.)
    assert 'hbo' in raw
    assert raw.info['sfreq'] == 3.
    assert raw.get_data().shape == (1, 900)
    assert np.max(raw.get_data()) < 1.2 * 1.e-6
    assert raw.annotations.description[0] == 'A'
    assert raw.annotations.duration[0] == 5
    assert np.min(np.diff(raw.annotations.onset)) > 15. + 5.
    assert np.max(np.diff(raw.annotations.onset)) < 45. + 5.
示例#6
0
def test_run_GLM():
    raw = simulate_nirs_raw(sig_dur=200, stim_dur=5.)
    design_matrix = make_first_level_design_matrix(raw,
                                                   stim_dur=5.,
                                                   drift_order=1,
                                                   drift_model='polynomial')
    glm_estimates = run_GLM(raw, design_matrix)

    assert len(glm_estimates) == len(raw.ch_names)

    # Check the estimate is correct within 10% error
    assert abs(glm_estimates["Simulated"].theta[0] - 1.e-6) < 0.1e-6

    # ensure we return the same type as nilearn to encourage compatibility
    _, ni_est = nilearn.glm.first_level.run_glm(
        raw.get_data(0).T, design_matrix.values)
    assert type(ni_est) == type(glm_estimates)
示例#7
0
def test_cropped_raw():
    # Ensure timing is correct for cropped signals
    raw = simulate_nirs_raw(sfreq=1.,
                            amplitude=1.,
                            sig_dur=300.,
                            stim_dur=1.,
                            isi_min=20.,
                            isi_max=40.)

    onsets = raw.annotations.onset
    onsets_after_crop = [onsets[idx] for idx in np.where(onsets > 100)]

    raw.crop(tmin=100)
    design_matrix = make_first_level_design_matrix(raw,
                                                   drift_order=0,
                                                   drift_model='polynomial')

    # 100 corrects for the crop time above
    # 4 is peak time after onset
    new_idx = np.round(onsets_after_crop[0][0]) - 100 + 4
    assert design_matrix["A"][new_idx] > 0.1
示例#8
0
def test_simulate_NIRS_multi_channel():

    raw = simulate_nirs_raw(sfreq=3.,
                            amplitude=[0., 2., 4.],
                            annot_desc=['Control', 'Cond_A', 'Cond_B'],
                            stim_dur=[5, 5, 5],
                            sig_dur=1500.,
                            isi_min=5.,
                            isi_max=15.,
                            hrf_model='spm')

    design_matrix = make_first_level_design_matrix(raw,
                                                   stim_dur=5.0,
                                                   drift_order=0,
                                                   drift_model='polynomial')

    assert len(design_matrix['Control']) == 1500 * 3
    assert len(design_matrix['Cond_A']) == 1500 * 3

    # Make sure no extra channels. Specifically the default isn't present.
    with pytest.raises(KeyError, match='A'):
        len(design_matrix['A'])
示例#9
0
def test_statsmodel_to_df(func):
    func = getattr(smf, func)
    np.random.seed(0)

    amplitude = 1.432

    df_cha = pd.DataFrame()
    for n in range(5):

        raw = simulate_nirs_raw(sfreq=3.,
                                amplitude=amplitude,
                                sig_dur=300.,
                                stim_dur=5.,
                                isi_min=15.,
                                isi_max=45.)
        raw._data += np.random.normal(0, np.sqrt(1e-12), raw._data.shape)
        design_matrix = make_first_level_design_matrix(raw, stim_dur=5.0)
        glm_est = run_glm(raw, design_matrix)
        with pytest.warns(RuntimeWarning, match='Non standard source detect'):
            cha = glm_est.to_dataframe()
        cha["ID"] = '%02d' % n
        df_cha = pd.concat([df_cha, cha], ignore_index=True)
    df_cha["theta"] = df_cha["theta"] * 1.0e6
    roi_model = func("theta ~ -1 + Condition", df_cha,
                     groups=df_cha["ID"]).fit()
    df = statsmodels_to_results(roi_model)
    assert type(df) == pd.DataFrame
    assert_allclose(df["Coef."]["Condition[A]"], amplitude, rtol=0.1)
    assert df["Significant"]["Condition[A]"]
    assert df.shape == (8, 8)

    roi_model = smf.rlm("theta ~ -1 + Condition", df_cha,
                        groups=df_cha["ID"]).fit()
    df = statsmodels_to_results(roi_model)
    assert type(df) == pd.DataFrame
    assert_allclose(df["Coef."]["Condition[A]"], amplitude, rtol=0.1)
    assert df["Significant"]["Condition[A]"]
    assert df.shape == (8, 8)
示例#10
0
def test_run_GLM():
    raw = simulate_nirs_raw(sig_dur=200, stim_dur=5.)
    design_matrix = make_first_level_design_matrix(raw,
                                                   stim_dur=5.,
                                                   drift_order=1,
                                                   drift_model='polynomial')
    glm_estimates = run_glm(raw, design_matrix)

    # Test backwards compatibility
    with pytest.deprecated_call(match='more comprehensive'):
        old_res = run_GLM(raw, design_matrix)
    assert old_res.keys() == glm_estimates.data.keys()
    assert (old_res["Simulated"].theta == glm_estimates.data["Simulated"].theta
            ).all()

    assert len(glm_estimates) == len(raw.ch_names)

    # Check the estimate is correct within 10% error
    assert abs(glm_estimates.pick("Simulated").theta()[0][0] - 1.e-6) < 0.1e-6

    # ensure we return the same type as nilearn to encourage compatibility
    _, ni_est = nilearn.glm.first_level.run_glm(
        raw.get_data(0).T, design_matrix.values)
    assert isinstance(glm_estimates._data, type(ni_est))
示例#11
0
# Here we look at the effect of the interstimulus interval on the
# expected haemodynamic response. We choose a few different
# maximum and minimum
# values for the ISI. Two repeats are plotted per
# ISI to illustrate the random selection.
# Some common high pass filter values from literature are shown in red.

sm = plt.cm.ScalarMappable(cmap='viridis', norm=plt.Normalize(vmin=0, vmax=60))
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(20, 10))
for rep in range(2):
    for column, min_isi in enumerate([0, 15]):
        for row, max_isi in enumerate([15, 30, 45, 60]):
            if max_isi >= min_isi:
                raw = simulate_nirs_raw(sfreq=4.,
                                        sig_dur=60 * 60,
                                        amplitude=1.,
                                        stim_dur=5.,
                                        isi_min=min_isi,
                                        isi_max=max_isi)
                raw._data[0] = raw._data[0] - np.mean(raw._data[0])
                raw.pick(picks='hbo').plot_psd(average=True,
                                               fmax=2,
                                               ax=axes[rep, column],
                                               show=False,
                                               color=sm.cmap(sm.norm(max_isi)),
                                               xscale='log')
                axes[rep, column].set_ylim(-60, 20)
                axes[rep, column].set_title(
                    'ISI: {} (s) to Max ISI'.format(min_isi))
                for filt in [0.01, 0.02, 0.05]:
                    axes[rep, column].axvline(x=filt,
                                              linestyle=":",