Ejemplo n.º 1
0
def test_locale_encoding(tmp_path):
    """Test NIRx encoding."""
    fname = tmp_path / 'latin'
    shutil.copytree(fname_nirx_15_2, fname)
    hdr_fname = op.join(fname, 'NIRS-2019-10-02_003.hdr')
    hdr = list()
    with open(hdr_fname, 'rb') as fid:
        hdr.extend(line for line in fid)
    # French
    hdr[2] = b'Date="jeu. 13 f\xe9vr. 2020"\r\n'
    with open(hdr_fname, 'wb') as fid:
        for line in hdr:
            fid.write(line)
    read_raw_nirx(fname, verbose='debug')
    # German
    hdr[2] = b'Date="mi 13 dez 2020"\r\n'
    with open(hdr_fname, 'wb') as fid:
        for line in hdr:
            fid.write(line)
    read_raw_nirx(fname, verbose='debug')
    # Italian
    hdr[2] = b'Date="ven 24 gen 2020"\r\n'
    hdr[3] = b'Time="10:57:41.454"\r\n'
    with open(hdr_fname, 'wb') as fid:
        for line in hdr:
            fid.write(line)
    raw = read_raw_nirx(fname, verbose='debug')
    want_dt = dt.datetime(
        2020, 1, 24, 10, 57, 41, 454000, tzinfo=dt.timezone.utc)
    assert raw.info['meas_date'] == want_dt
Ejemplo n.º 2
0
def test_nirsport_v1_w_bad_sat(preload, meas_date):
    """Test NIRSport1 file with NaNs."""
    fname = nirsport1_w_fullsat
    raw = read_raw_nirx(fname, preload=preload)
    data = raw.get_data()
    assert not np.isnan(data).any()
    assert len(raw.annotations) == 5
    # annotated version and ignore should have same data but different annot
    raw_ignore = read_raw_nirx(fname, saturated='ignore', preload=preload)
    assert_allclose(raw_ignore.get_data(), data)
    assert len(raw_ignore.annotations) == 2
    assert not any('NAN' in d for d in raw_ignore.annotations.description)
    # nan version should not have same data, but we can give it the same annot
    raw_nan = read_raw_nirx(fname, saturated='nan', preload=preload)
    data_nan = raw_nan.get_data()
    assert np.isnan(data_nan).any()
    assert not np.allclose(raw_nan.get_data(), data)
    raw_nan_annot = raw_ignore.copy()
    if meas_date is None:
        raw.set_meas_date(None)
        raw_nan.set_meas_date(None)
        raw_nan_annot.set_meas_date(None)
    nan_annots = annotate_nan(raw_nan)
    assert nan_annots.orig_time == raw_nan.info["meas_date"]
    raw_nan_annot.set_annotations(nan_annots)
    use_mask = np.where(raw.annotations.description == 'BAD_SATURATED')
    for key in ('onset', 'duration'):
        a = getattr(raw_nan_annot.annotations, key)[::2]  # one ch in each
        b = getattr(raw.annotations, key)[use_mask]  # two chs in each
        assert_allclose(a, b)
Ejemplo n.º 3
0
def test_fnirs_check_bads(fname):
    """Test checking of bad markings."""
    # No bad channels, so these should all pass
    raw = read_raw_nirx(fname)
    _fnirs_check_bads(raw.info)
    raw = optical_density(raw)
    _fnirs_check_bads(raw.info)
    raw = beer_lambert_law(raw)
    _fnirs_check_bads(raw.info)

    # Mark pairs of bad channels, so these should all pass
    raw = read_raw_nirx(fname)
    raw.info['bads'] = raw.ch_names[0:2]
    _fnirs_check_bads(raw.info)
    raw = optical_density(raw)
    _fnirs_check_bads(raw.info)
    raw = beer_lambert_law(raw)
    _fnirs_check_bads(raw.info)

    # Mark single channel as bad, so these should all fail
    raw = read_raw_nirx(fname)
    raw.info['bads'] = raw.ch_names[0:1]
    pytest.raises(RuntimeError, _fnirs_check_bads, raw.info)
    with pytest.raises(RuntimeError, match='bad labelling'):
        raw = optical_density(raw)
    pytest.raises(RuntimeError, _fnirs_check_bads, raw.info)
    with pytest.raises(RuntimeError, match='bad labelling'):
        raw = beer_lambert_law(raw)
    pytest.raises(RuntimeError, _fnirs_check_bads, raw.info)
Ejemplo n.º 4
0
def test_nirx_dat_warn(tmp_path):
    """Test reading NIRX files when missing data."""
    shutil.copytree(fname_nirx_15_2_short, str(tmp_path) + "/data/")
    os.rename(tmp_path / "data" / "NIRS-2019-08-23_001.dat",
              tmp_path / "data" / "NIRS-2019-08-23_001.tmp")
    fname = tmp_path / "data" / "NIRS-2019-08-23_001.hdr"
    with pytest.raises(RuntimeWarning, match='A single dat'):
        read_raw_nirx(fname, preload=True)
Ejemplo n.º 5
0
def test_encoding(tmpdir):
    """Test NIRx encoding."""
    fname = str(tmpdir.join('latin'))
    shutil.copytree(fname_nirx_15_2, fname)
    hdr_fname = op.join(fname, 'NIRS-2019-10-02_003.hdr')
    hdr = list()
    with open(hdr_fname, 'rb') as fid:
        hdr.extend(line for line in fid)
    hdr[2] = b'Date="jeu. 13 f\xe9vr. 2020"\r\n'
    with open(hdr_fname, 'wb') as fid:
        for line in hdr:
            fid.write(line)
    # smoke test
    read_raw_nirx(fname)
Ejemplo n.º 6
0
def test_encoding(tmp_path):
    """Test NIRx encoding."""
    fname = tmp_path / 'latin'
    shutil.copytree(fname_nirx_15_2, fname)
    hdr_fname = op.join(fname, 'NIRS-2019-10-02_003.hdr')
    hdr = list()
    with open(hdr_fname, 'rb') as fid:
        hdr.extend(line for line in fid)
    hdr[2] = b'Date="jeu. 13 f\xe9vr. 2020"\r\n'
    with open(hdr_fname, 'wb') as fid:
        for line in hdr:
            fid.write(line)
    # smoke test
    with pytest.raises(RuntimeWarning, match='Extraction of measurement date'):
        read_raw_nirx(fname)
Ejemplo n.º 7
0
def test_label_finder():
    """Test locating labels."""
    raw = read_raw_nirx(fname_nirx_15_3_short, preload=True)
    reference_locations = _generate_montage_locations()

    # Test central head position source
    raw_tmp = raw.copy().pick(25)
    assert _find_closest_standard_location(
        raw_tmp.info['chs'][0]['loc'][3:6],
        reference_locations) == "Cz"

    # Test right auditory position detector
    raw_tmp = raw.copy().pick(4)
    assert _find_closest_standard_location(
        raw_tmp.info['chs'][0]['loc'][6:9],
        reference_locations) == "T8"

    # Test right auditory position source
    raw_tmp = raw.copy().pick(4)
    assert _find_closest_standard_location(
        raw_tmp.info['chs'][0]['loc'][3:6],
        reference_locations) == "TP8"

    # Test left auditory position source
    raw_tmp = raw.copy().pick(1)
    assert _find_closest_standard_location(
        raw_tmp.info['chs'][0]['loc'][3:6],
        reference_locations) == "T7"

    # Test left auditory position detector
    raw_tmp = raw.copy().pick(1)
    assert _find_closest_standard_location(
        raw_tmp.info['chs'][0]['loc'][6:9],
        reference_locations) == "TP7"
Ejemplo n.º 8
0
def test_fold_workflow():
    # Read raw data
    raw = read_raw_nirx(fname_nirx_15_3_short, preload=True)
    reference_locations = _generate_montage_locations()
    channel_of_interest = raw.copy().pick(1)

    # Get source and detector labels
    source_locs = channel_of_interest.info['chs'][0]['loc'][3:6]
    source_label = _find_closest_standard_location(source_locs,
                                                   reference_locations)
    assert source_label == "T7"

    detector_locs = channel_of_interest.info['chs'][0]['loc'][6:9]
    detector_label = _find_closest_standard_location(detector_locs,
                                                     reference_locations)
    assert detector_label == "TP7"

    # Find correct fOLD elements
    tbl = _read_fold_xls(foldfile, atlas="Juelich")
    tbl = tbl.query("Source == @source_label").\
        query("Detector == @detector_label")

    # Query region of interest
    specificity = tbl.query("Landmark == 'L Mid Orbital Gyrus'")["Specificity"]
    assert specificity.values == 12.34
def test_temporal_derivative_distribution_repair(fname, tmp_path):
    """Test running artifact rejection."""
    raw = read_raw_nirx(fname)
    raw_od = optical_density(raw)
    raw_hb = beer_lambert_law(raw_od)

    # With optical densities
    # Add a baseline shift artifact about half way through data
    max_shift = np.max(np.diff(raw_od._data[0]))
    shift_amp = 5 * max_shift
    raw_od._data[0, 0:30] = raw_od._data[0, 0:30] - shift_amp
    # make one channel zero std
    raw_od._data[1] = 0.
    raw_od._data[2] = 1.
    assert np.max(np.diff(raw_od._data[0])) > shift_amp
    # Ensure that applying the algorithm reduces the step change
    raw_od = tddr(raw_od)
    assert np.max(np.diff(raw_od._data[0])) < shift_amp
    assert_allclose(raw_od._data[1], 0.)  # unchanged
    assert_allclose(raw_od._data[2], 1.)  # unchanged

    # With Hb
    # Add a baseline shift artifact about half way through data
    max_shift = np.max(np.diff(raw_hb._data[0]))
    shift_amp = 5 * max_shift
    raw_hb._data[0, 0:30] = raw_hb._data[0, 0:30] - (1.1 * shift_amp)
    # make one channel zero std
    raw_hb._data[1] = 0.
    raw_hb._data[2] = 1.
    assert np.max(np.diff(raw_hb._data[0])) > shift_amp
    # Ensure that applying the algorithm reduces the step change
    raw_hb = tddr(raw_hb)
    assert np.max(np.diff(raw_hb._data[0])) < shift_amp
    assert_allclose(raw_hb._data[1], 0.)  # unchanged
    assert_allclose(raw_hb._data[2], 1.)  # unchanged
Ejemplo n.º 10
0
def test_beer_lambert_v_matlab():
    """Compare MNE results to MATLAB toolbox."""
    from pymatreader import read_mat
    raw = read_raw_nirx(fname_nirx_15_0)
    raw = optical_density(raw)
    raw = beer_lambert_law(raw, ppf=0.121)
    raw._data *= 1e6  # Scale to uM for comparison to MATLAB

    matlab_fname = op.join(testing_path, 'NIRx', 'nirscout', 'validation',
                           'nirx_15_0_recording_bl.mat')
    matlab_data = read_mat(matlab_fname)

    matlab_names = ["_"] * len(raw.ch_names)
    for idx in range(len(raw.ch_names)):
        matlab_names[idx] = ("S" + str(int(matlab_data['sources'][idx])) +
                             "_D" + str(int(matlab_data['detectors'][idx])) +
                             " " + matlab_data['type'][idx])
    matlab_to_mne = np.argsort(matlab_names)

    for idx in range(raw.get_data().shape[0]):

        matlab_idx = matlab_to_mne[idx]

        mean_error = np.mean(matlab_data['data'][:, matlab_idx] -
                             raw._data[idx])
        assert mean_error < 0.1
        matlab_name = ("S" + str(int(matlab_data['sources'][matlab_idx])) +
                       "_D" + str(int(matlab_data['detectors'][matlab_idx])) +
                       " " + matlab_data['type'][matlab_idx])
        assert raw.info['ch_names'][idx] == matlab_name
Ejemplo n.º 11
0
def test_optical_density_zeromean():
    """Test that optical density can process zero mean data."""
    raw = read_raw_nirx(fname_nirx, preload=True)
    raw._data[4] -= np.mean(raw._data[4])
    with pytest.warns(RuntimeWarning, match='Negative'):
        raw = optical_density(raw)
    assert 'fnirs_od' in raw
def test_scalp_coupling_index(fname, fmt, tmpdir):
    """Test converting NIRX files."""
    assert fmt in ('nirx', 'fif')
    raw = read_raw_nirx(fname)
    raw = optical_density(raw)
    sci = scalp_coupling_index(raw)

    # All values should be between -1 and +1
    assert_array_less(sci, 1.0)
    assert_array_less(sci * -1.0, 1.0)

    # Fill in some data with known correlation values
    rng = np.random.RandomState(0)
    new_data = rng.rand(raw._data[0].shape[0])
    # Set first two channels to perfect correlation
    raw._data[0] = new_data
    raw._data[1] = new_data
    # Set next two channels to perfect correlation
    raw._data[2] = new_data
    raw._data[3] = new_data * 0.3  # check scale invariance
    # Set next two channels to anti correlation
    raw._data[4] = new_data
    raw._data[5] = new_data * -1.0
    # Set next two channels to be uncorrelated
    raw._data[6] = new_data
    raw._data[7] = rng.rand(raw._data[0].shape[0])
    # Check values
    sci = scalp_coupling_index(raw)
    assert_allclose(sci[0:6], [1, 1, 1, 1, -1, -1], atol=0.01)
    assert np.abs(sci[6]) < 0.5
    assert np.abs(sci[7]) < 0.5
Ejemplo n.º 13
0
def test_snirf_write(fname, tmpdir):
    """Test reading NIRX files."""
    raw_orig = read_raw_nirx(fname, preload=True)
    write_raw_snirf(raw_orig, tmpdir.join('test_raw.snirf'))
    raw = read_raw_snirf(tmpdir.join('test_raw.snirf'))

    # Check annotations are the same
    assert_allclose(raw.annotations.onset, raw_orig.annotations.onset)
    assert_allclose([float(d) for d in raw.annotations.description],
                    [float(d) for d in raw_orig.annotations.description])
    assert_allclose(raw.annotations.duration, raw_orig.annotations.duration)

    # Check data is the same
    assert_allclose(raw.get_data(), raw_orig.get_data())

    assert abs(raw_orig.info["meas_date"] - raw.info["meas_date"]) < \
           datetime.timedelta(seconds=1)

    # Check info object is the same
    obj_diff = object_diff(raw.info, raw_orig.info)
    diffs = ''
    for line in obj_diff.splitlines():
        if ('logno' not in line) and ('scanno' not in line) and\
                ('datetime mismatch' not in line):
            # logno and scanno are not used in processing
            diffs += f'\n{line}'
    assert diffs == ''
Ejemplo n.º 14
0
def test_nirx_15_2():
    """Test reading NIRX files."""
    raw = read_raw_nirx(fname_nirx_15_2, preload=True)

    # Test data import
    assert raw._data.shape == (64, 67)
    assert raw.info['sfreq'] == 3.90625

    # Test channel naming
    assert raw.info['ch_names'][:4] == [
        "S1_D1 760", "S1_D1 850", "S1_D10 760", "S1_D10 850"
    ]

    # Test info import
    assert raw.info['subject_info'] == dict(sex=1, first_name="TestRecording")

    # Test trigger events
    assert_array_equal(raw.annotations.description, ['4.0', '6.0', '2.0'])

    # Test location of detectors
    allowed_dist_error = 0.0002
    locs = [ch['loc'][6:9] for ch in raw.info['chs']]
    head_mri_t, _ = _get_trans('fsaverage', 'head', 'mri')
    mni_locs = apply_trans(head_mri_t, locs)

    assert raw.info['ch_names'][0][3:5] == 'D1'
    assert_allclose(mni_locs[0], [-0.0292, 0.0852, -0.0142],
                    atol=allowed_dist_error)

    assert raw.info['ch_names'][15][3:5] == 'D4'
    assert_allclose(mni_locs[15], [-0.0739, -0.0756, -0.0075],
                    atol=allowed_dist_error)
Ejemplo n.º 15
0
def test_beer_lambert(fname, fmt, tmpdir):
    """Test converting NIRX files."""
    assert fmt in ('nirx', 'fif')
    raw = read_raw_nirx(fname)
    if fmt == 'fif':
        raw.save(tmpdir.join('test_raw.fif'))
        raw = read_raw_fif(tmpdir.join('test_raw.fif'))
    assert 'fnirs_cw_amplitude' in raw
    with pytest.deprecated_call():
        assert 'fnirs_raw' in raw
    assert 'fnirs_od' not in raw
    raw = optical_density(raw)
    _validate_type(raw, BaseRaw, 'raw')
    assert 'fnirs_cw_amplitude' not in raw
    with pytest.deprecated_call():
        assert 'fnirs_raw' not in raw
    assert 'fnirs_od' in raw
    assert 'hbo' not in raw
    raw = beer_lambert_law(raw)
    _validate_type(raw, BaseRaw, 'raw')
    assert 'fnirs_cw_amplitude' not in raw
    with pytest.deprecated_call():
        assert 'fnirs_raw' not in raw
    assert 'fnirs_od' not in raw
    assert 'hbo' in raw
    assert 'hbr' in raw
Ejemplo n.º 16
0
def test_fnirs_picks():
    """Test picking of fnirs types after different conversions."""
    raw = read_raw_nirx(fname_nirx_15_0)
    picks = _picks_to_idx(raw.info, 'fnirs_cw_amplitude')
    assert len(picks) == len(raw.ch_names)
    raw_subset = raw.copy().pick(picks='fnirs_cw_amplitude')
    for ch in raw_subset.info["chs"]:
        assert ch['coil_type'] == FIFF.FIFFV_COIL_FNIRS_CW_AMPLITUDE

    picks = _picks_to_idx(raw.info, ['fnirs_cw_amplitude', 'fnirs_od'])
    assert len(picks) == len(raw.ch_names)
    picks = _picks_to_idx(raw.info, ['fnirs_cw_amplitude', 'fnirs_od', 'hbr'])
    assert len(picks) == len(raw.ch_names)
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'fnirs_od')
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'hbo')
    pytest.raises(ValueError, _picks_to_idx, raw.info, ['hbr'])
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'fnirs_fd_phase')
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'junk')

    raw = optical_density(raw)
    picks = _picks_to_idx(raw.info, 'fnirs_od')
    assert len(picks) == len(raw.ch_names)
    raw_subset = raw.copy().pick(picks='fnirs_od')
    for ch in raw_subset.info["chs"]:
        assert ch['coil_type'] == FIFF.FIFFV_COIL_FNIRS_OD

    picks = _picks_to_idx(raw.info, ['fnirs_cw_amplitude', 'fnirs_od'])
    assert len(picks) == len(raw.ch_names)
    picks = _picks_to_idx(raw.info, ['fnirs_cw_amplitude', 'fnirs_od', 'hbr'])
    assert len(picks) == len(raw.ch_names)
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'fnirs_cw_amplitude')
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'hbo')
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'hbr')
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'fnirs_fd_phase')
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'junk')

    raw = beer_lambert_law(raw)
    picks = _picks_to_idx(raw.info, 'hbo')
    assert len(picks) == len(raw.ch_names) / 2
    raw_subset = raw.copy().pick(picks='hbo')
    for ch in raw_subset.info["chs"]:
        assert ch['coil_type'] == FIFF.FIFFV_COIL_FNIRS_HBO

    picks = _picks_to_idx(raw.info, ['hbr'])
    assert len(picks) == len(raw.ch_names) / 2
    raw_subset = raw.copy().pick(picks=['hbr'])
    for ch in raw_subset.info["chs"]:
        assert ch['coil_type'] == FIFF.FIFFV_COIL_FNIRS_HBR

    picks = _picks_to_idx(raw.info, ['hbo', 'hbr'])
    assert len(picks) == len(raw.ch_names)
    picks = _picks_to_idx(raw.info, ['hbo', 'fnirs_od', 'hbr'])
    assert len(picks) == len(raw.ch_names)
    picks = _picks_to_idx(raw.info, ['hbo', 'fnirs_od'])
    assert len(picks) == len(raw.ch_names) / 2
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'fnirs_cw_amplitude')
    pytest.raises(ValueError, _picks_to_idx, raw.info, ['fnirs_od'])
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'junk')
    pytest.raises(ValueError, _picks_to_idx, raw.info, 'fnirs_fd_phase')
Ejemplo n.º 17
0
def test_channel_specificity(monkeypatch, tmp_path, fold_files):
    raw = read_raw_nirx(fname_nirx_15_3_short, preload=True)
    raw.pick(range(2))
    kwargs = dict()
    n_want = 6
    if fold_files is list:
        kwargs = dict(fold_files=[foldfile])
    elif fold_files is str:
        kwargs = dict(fold_files=tmp_path)
        n_want *= 2
    else:
        assert fold_files is None
        monkeypatch.setenv('MNE_NIRS_FOLD_PATH', str(tmp_path))
        assert len(kwargs) == 0
        with pytest.raises(FileNotFoundError, match=r'fold_files\[0\] does.*'):
            fold_channel_specificity(raw)
        n_want *= 2
    copyfile(foldfile, tmp_path / '10-10.xls')
    copyfile(foldfile, tmp_path / '10-5.xls')
    res = fold_channel_specificity(raw, **kwargs)
    assert len(res) == 2
    assert res[0].shape == (n_want, 14)
    montage = make_standard_montage(
        'standard_1005', head_size=0.09700884729534559)
    fids = read_fiducials(
        Path(mne.__file__).parent / 'data' / 'fsaverage' /
        'fsaverage-fiducials.fif')[0]
    for f in fids:
        f['coord_frame'] = montage.dig[0]['coord_frame']
    montage.dig[:3] = fids
    S, D = raw.ch_names[0].split()[0].split('_')
    assert S == 'S1' and D == 'D2'
    montage.rename_channels({'PO8': S, 'P6': D})  # not in the tables!
    # taken from standard_1020.elc
    s_mri = np.array([55.6666, -97.6251, 2.7300]) / 1000.
    d_mri = np.array([67.8877, -75.9043, 28.0910]) / 1000.
    trans = mne.transforms._get_trans('fsaverage', 'mri', 'head')[0]
    ch_pos = montage.get_positions()['ch_pos']
    assert_allclose(ch_pos[S], s_mri, atol=1e-6)
    assert_allclose(ch_pos[D], d_mri, atol=1e-6)
    raw.set_montage(montage)
    montage = transform_to_head(montage)
    s_head = mne.transforms.apply_trans(trans, s_mri)
    d_head = mne.transforms.apply_trans(trans, d_mri)
    assert_allclose(montage._get_ch_pos()['S1'], s_head, atol=1e-6)
    assert_allclose(montage._get_ch_pos()['D2'], d_head, atol=1e-6)
    for ch in raw.info['chs']:
        assert_allclose(ch['loc'][3:6], s_head, atol=1e-6)
        assert_allclose(ch['loc'][6:9], d_head, atol=1e-6)
    res_1 = fold_channel_specificity(raw, **kwargs)[0]
    assert res_1.shape == (0, 14)
    # TODO: This is wrong, should be P08 not P08h, and distance should be 0 mm!
    with pytest.warns(RuntimeWarning, match='.*PO8h?/P6.*TP8/T8.*'):
        res_1 = fold_channel_specificity(raw, interpolate=True, **kwargs)[0]
    montage.rename_channels({S: D, D: S})  # reversed
    with pytest.warns(RuntimeWarning, match='.*PO8h?/P6.*TP8/T8.*'):
        res_2 = fold_channel_specificity(raw, interpolate=True, **kwargs)[0]
    # We should check the whole thing, but this is probably good enough
    assert (res_1['Specificity'] == res_2['Specificity']).all()
Ejemplo n.º 18
0
def test_nirx_missing_evt(tmp_path):
    """Test reading NIRX files when missing data."""
    shutil.copytree(fname_nirx_15_2_short, str(tmp_path) + "/data/")
    os.rename(tmp_path / "data" / "NIRS-2019-08-23_001.evt",
              tmp_path / "data" / "NIRS-2019-08-23_001.xxx")
    fname = tmp_path / "data" / "NIRS-2019-08-23_001.hdr"
    raw = read_raw_nirx(fname, preload=True)
    assert raw.annotations.onset.shape == (0, )
Ejemplo n.º 19
0
def test_nirx_hdr_load():
    """Test reading NIRX files using path to header file."""
    fname = fname_nirx_15_2_short + "/NIRS-2019-08-23_001.hdr"
    raw = read_raw_nirx(fname, preload=True)

    # Test data import
    assert raw._data.shape == (26, 145)
    assert raw.info['sfreq'] == 12.5
Ejemplo n.º 20
0
def test_snirf_nobday(fname, tmpdir):
    """Ensure writing works when no birthday is present."""
    raw_orig = read_raw_nirx(fname, preload=True)
    raw_orig.info['subject_info'].pop('birthday', None)
    test_file = tmpdir.join('test_raw.snirf')
    write_raw_snirf(raw_orig, test_file)
    raw = read_raw_snirf(test_file)
    assert_allclose(raw.get_data(), raw_orig.get_data())
Ejemplo n.º 21
0
def test_channel_order(fname, want_order):
    """Test that logical channel order is preserved."""
    raw = read_raw_nirx(fname)
    ch_names = raw.ch_names
    prefixes = [ch_name.split()[0] for ch_name in ch_names]
    assert prefixes[::2] == prefixes[1::2]
    prefixes = prefixes[::2]
    assert prefixes == want_order
Ejemplo n.º 22
0
def test_landmark_specificity():
    raw = read_raw_nirx(fname_nirx_15_3_short, preload=True)
    with pytest.warns(RuntimeWarning, match='No fOLD table entry'):
        res = fold_landmark_specificity(raw, "L Superior Frontal Gyrus",
                                        [foldfile], interpolate=True)
    assert len(res) == len(raw.ch_names)
    assert np.max(res) <= 100
    assert np.min(res) >= 0
Ejemplo n.º 23
0
def test_nirx_15_0():
    """Test reading NIRX files."""
    raw = read_raw_nirx(fname_nirx_15_0, preload=True)

    # Test data import
    assert raw._data.shape == (20, 92)
    assert raw.info['sfreq'] == 6.25
    assert raw.info['meas_date'] == dt.datetime(2019,
                                                10,
                                                27,
                                                13,
                                                53,
                                                34,
                                                209000,
                                                tzinfo=dt.timezone.utc)

    # Test channel naming
    assert raw.info['ch_names'][:12] == [
        "S1_D1 760", "S1_D1 850", "S2_D2 760", "S2_D2 850", "S3_D3 760",
        "S3_D3 850", "S4_D4 760", "S4_D4 850", "S5_D5 760", "S5_D5 850",
        "S6_D6 760", "S6_D6 850"
    ]

    # Test info import
    assert raw.info['subject_info'] == {
        'birthday': (2004, 10, 27),
        'first_name': 'NIRX',
        'last_name': 'Test',
        'sex': FIFF.FIFFV_SUBJ_SEX_UNKNOWN,
        'his_id': "NIRX_Test"
    }

    # Test trigger events
    assert_array_equal(raw.annotations.description, ['1.0', '2.0', '2.0'])

    # Test location of detectors
    allowed_dist_error = 0.0002
    locs = [ch['loc'][6:9] for ch in raw.info['chs']]
    head_mri_t, _ = _get_trans('fsaverage', 'head', 'mri')
    mni_locs = apply_trans(head_mri_t, locs)

    assert raw.info['ch_names'][0][3:5] == 'D1'
    assert_allclose(mni_locs[0], [0.0287, -0.1143, -0.0332],
                    atol=allowed_dist_error)

    assert raw.info['ch_names'][15][3:5] == 'D8'
    assert_allclose(mni_locs[15], [-0.0693, -0.0480, 0.0657],
                    atol=allowed_dist_error)

    # Test distance between optodes matches values from
    allowed_distance_error = 0.0002

    assert_allclose(source_detector_distances(
        raw.copy().pick("S1_D1 760").info), [0.0300],
                    atol=allowed_distance_error)
    assert_allclose(source_detector_distances(
        raw.copy().pick("S7_D7 760").info), [0.0392],
                    atol=allowed_distance_error)
Ejemplo n.º 24
0
def test_optical_density():
    """Test return type for optical density."""
    raw = read_raw_nirx(fname_nirx, preload=False)
    assert 'fnirs_cw_amplitude' in raw
    assert 'fnirs_od' not in raw
    raw = optical_density(raw)
    _validate_type(raw, BaseRaw, 'raw')
    assert 'fnirs_cw_amplitude' not in raw
    assert 'fnirs_od' in raw
Ejemplo n.º 25
0
def test_fnirs_channel_naming_and_order_readers(fname):
    """Ensure fNIRS channel checking on standard readers."""
    # fNIRS data requires specific channel naming and ordering.

    # All standard readers should pass tests
    raw = read_raw_nirx(fname)
    freqs = np.unique(_channel_frequencies(raw.info))
    assert_array_equal(freqs, [760, 850])
    chroma = np.unique(_channel_chromophore(raw.info))
    assert len(chroma) == 0

    picks = _check_channels_ordered(raw.info, freqs)
    assert len(picks) == len(raw.ch_names)  # as all fNIRS only data

    # Check that dropped channels are detected
    # For each source detector pair there must be two channels,
    # removing one should throw an error.
    raw_dropped = raw.copy().drop_channels(raw.ch_names[4])
    with pytest.raises(ValueError, match='not ordered correctly'):
        _check_channels_ordered(raw_dropped.info, freqs)

    # The ordering must be increasing for the pairs, if provided
    raw_names_reversed = raw.copy().ch_names
    raw_names_reversed.reverse()
    raw_reversed = raw.copy().pick_channels(raw_names_reversed, ordered=True)
    with pytest.raises(ValueError, match='The frequencies.*sorted.*'):
        _check_channels_ordered(raw_reversed.info, [850, 760])
    # So if we flip the second argument it should pass again
    picks = _check_channels_ordered(raw_reversed.info, freqs)
    got_first = set(raw_reversed.ch_names[pick].split()[1]
                    for pick in picks[::2])
    assert got_first == {'760'}
    got_second = set(raw_reversed.ch_names[pick].split()[1]
                     for pick in picks[1::2])
    assert got_second == {'850'}

    # Check on OD data
    raw = optical_density(raw)
    freqs = np.unique(_channel_frequencies(raw.info))
    assert_array_equal(freqs, [760, 850])
    chroma = np.unique(_channel_chromophore(raw.info))
    assert len(chroma) == 0
    picks = _check_channels_ordered(raw.info, freqs)
    assert len(picks) == len(raw.ch_names)  # as all fNIRS only data

    # Check on haemoglobin data
    raw = beer_lambert_law(raw)
    freqs = np.unique(_channel_frequencies(raw.info))
    assert len(freqs) == 0
    assert len(_channel_chromophore(raw.info)) == len(raw.ch_names)
    chroma = np.unique(_channel_chromophore(raw.info))
    assert_array_equal(chroma, ["hbo", "hbr"])
    picks = _check_channels_ordered(raw.info, chroma)
    assert len(picks) == len(raw.ch_names)
    with pytest.raises(ValueError, match='chromophore in info'):
        _check_channels_ordered(raw.info, ["hbr", "hbo"])
Ejemplo n.º 26
0
def fnirs_epochs():
    """Create an fnirs epoch structure."""
    raw_intensity = read_raw_nirx(fname_nirx, preload=False)
    raw_od = optical_density(raw_intensity)
    raw_haemo = beer_lambert_law(raw_od, ppf=6.)
    evts, _ = events_from_annotations(raw_haemo, event_id={'1.0': 1})
    evts_dct = {'A': 1}
    tn, tx = -1, 2
    epochs = Epochs(raw_haemo, evts, event_id=evts_dct, tmin=tn, tmax=tx)
    return epochs
Ejemplo n.º 27
0
def test_nirsport_v1_w_sat():
    """Test NIRSport1 file with NaNs but not in channel of interest."""
    raw = read_raw_nirx(nirsport1_w_sat)

    # Test data import
    data = raw.get_data()
    assert data.shape == (26, 176)
    assert raw.info['sfreq'] == 10.416667
    assert np.sum(np.isnan(data)) == 0

    raw = read_raw_nirx(nirsport1_w_sat, saturated='nan')
    data = raw.get_data()
    assert data.shape == (26, 176)
    assert np.sum(np.isnan(data)) == 0

    raw = read_raw_nirx(nirsport1_w_sat, saturated='annotate')
    data = raw.get_data()
    assert data.shape == (26, 176)
    assert np.sum(np.isnan(data)) == 0
Ejemplo n.º 28
0
def test_optical_density():
    """Test return type for optical density."""
    raw = read_raw_nirx(fname_nirx, preload=False)
    assert 'fnirs_cw_amplitude' in raw
    assert 'fnirs_od' not in raw
    raw = optical_density(raw)
    _validate_type(raw, BaseRaw, 'raw')
    assert 'fnirs_cw_amplitude' not in raw
    assert 'fnirs_od' in raw
    with pytest.raises(RuntimeError, match='on continuous wave'):
        optical_density(raw)
Ejemplo n.º 29
0
def test_nirsport_v1_wo_sat():
    """Test NIRSport1 file with no saturation."""
    raw = read_raw_nirx(nirsport1_wo_sat, preload=True)

    # Test data import
    assert raw._data.shape == (26, 164)
    assert raw.info['sfreq'] == 10.416667

    # By default real data is returned
    assert np.sum(np.isnan(raw.get_data())) == 0

    raw = read_raw_nirx(nirsport1_wo_sat, preload=True, saturated='nan')
    data = raw.get_data()
    assert data.shape == (26, 164)
    assert np.sum(np.isnan(data)) == 0

    raw = read_raw_nirx(nirsport1_wo_sat, saturated='annotate')
    data = raw.get_data()
    assert data.shape == (26, 164)
    assert np.sum(np.isnan(data)) == 0
Ejemplo n.º 30
0
def test_nirsport_v2_matches_snirf(fname_nirx, fname_snirf):
    """Test NIRSport2 raw files return same data as snirf."""
    raw = read_raw_nirx(fname_nirx, preload=True)
    raw_snirf = read_raw_snirf(fname_snirf, preload=True)

    assert_allclose(raw._data, raw_snirf._data)

    # Check the timing of annotations match (naming is different)
    assert_allclose(raw.annotations.onset, raw_snirf.annotations.onset)

    assert_array_equal(raw.ch_names, raw_snirf.ch_names)