Exemple #1
0
def test_bvct_dig_montage_old_api():  # XXX: to remove in 0.20
    """Test BrainVision CapTrak XML dig montage support."""
    with pytest.warns(RuntimeWarning, match='Using "m" as unit for BVCT file'):
        read_dig_montage(bvct=bvct_dig_montage_fname, unit='m')

    with pytest.deprecated_call():
        dig_montage = read_dig_montage(bvct=bvct_dig_montage_fname)

    # test round-trip IO
    temp_dir = _TempDir()
    fname_temp = op.join(temp_dir, 'bvct_test.fif')
    _check_roundtrip(dig_montage, fname_temp)

    with pytest.deprecated_call():
        # nasion
        assert_almost_equal(dig_montage.nasion[0], 0)
        assert_almost_equal(dig_montage.nasion[2], 0)
        # lpa and rpa
        assert_allclose(dig_montage.lpa[1:], 0, atol=1e-16)
        assert_allclose(dig_montage.rpa[1:], 0, atol=1e-16)

    # Test accuracy and embedding within raw object
    raw_bv = read_raw_brainvision(bv_raw_fname)
    with pytest.warns(RuntimeWarning, match='Did not set.*channel pos'):
        raw_bv.set_montage(dig_montage)
    test_raw_bv = read_raw_fif(bv_fif_fname)

    assert_equal(len(raw_bv.ch_names), len(test_raw_bv.ch_names))
    for ch_raw, ch_test_raw in zip(raw_bv.info['chs'],
                                   test_raw_bv.info['chs']):
        assert_equal(ch_raw['ch_name'], ch_test_raw['ch_name'])
        assert_equal(ch_raw['coord_frame'], FIFF.FIFFV_COORD_HEAD)
        assert_allclose(ch_raw['loc'], ch_test_raw['loc'], atol=1e-7)
    assert_dig_allclose(raw_bv.info, test_raw_bv.info)
Exemple #2
0
def test_set_dig_montage():
    """Test applying DigMontage to inst."""
    # Extensive testing of applying `dig` to info is done in test_meas_info
    # with `test_make_dig_points`.
    names = ['nasion', 'lpa', 'rpa', '1', '2', '3', '4', '5']
    hsp_points = _read_dig_points(hsp)
    elp_points = _read_dig_points(elp)
    nasion, lpa, rpa = elp_points[:3]
    nm_trans = get_ras_to_neuromag_trans(nasion, lpa, rpa)
    elp_points = apply_trans(nm_trans, elp_points)
    nasion, lpa, rpa = elp_points[:3]
    hsp_points = apply_trans(nm_trans, hsp_points)

    montage = read_dig_montage(hsp,
                               hpi,
                               elp,
                               names,
                               transform=True,
                               dev_head_t=True)
    temp_dir = _TempDir()
    fname_temp = op.join(temp_dir, 'test.fif')
    montage.save(fname_temp)
    with pytest.deprecated_call():
        montage_read = read_dig_montage(fif=fname_temp)
    for use_mon in (montage, montage_read):
        info = create_info(['Test Ch'], 1e3, ['eeg'])
        with pytest.warns(None):  # warns on one run about not all positions
            _set_montage(info, use_mon)
        hs = np.array([
            p['r'] for i, p in enumerate(info['dig'])
            if p['kind'] == FIFF.FIFFV_POINT_EXTRA
        ])
        nasion_dig = np.array([
            p['r'] for p in info['dig'] if all([
                p['ident'] == FIFF.FIFFV_POINT_NASION, p['kind'] ==
                FIFF.FIFFV_POINT_CARDINAL
            ])
        ])
        lpa_dig = np.array([
            p['r'] for p in info['dig'] if all([
                p['ident'] == FIFF.FIFFV_POINT_LPA, p['kind'] ==
                FIFF.FIFFV_POINT_CARDINAL
            ])
        ])
        rpa_dig = np.array([
            p['r'] for p in info['dig'] if all([
                p['ident'] == FIFF.FIFFV_POINT_RPA, p['kind'] ==
                FIFF.FIFFV_POINT_CARDINAL
            ])
        ])
        hpi_dig = np.array(
            [p['r'] for p in info['dig'] if p['kind'] == FIFF.FIFFV_POINT_HPI])
        assert_allclose(hs, hsp_points, atol=1e-7)
        assert_allclose(nasion_dig.ravel(), nasion, atol=1e-7)
        assert_allclose(lpa_dig.ravel(), lpa, atol=1e-7)
        assert_allclose(rpa_dig.ravel(), rpa, atol=1e-7)
        assert_allclose(hpi_dig, elp_points[3:], atol=1e-7)
Exemple #3
0
def test_fif_dig_montage():
    """Test FIF dig montage support."""
    with pytest.deprecated_call():
        dig_montage = read_dig_montage(fif=fif_dig_montage_fname)

    # test round-trip IO
    temp_dir = _TempDir()
    fname_temp = op.join(temp_dir, 'test.fif')
    _check_roundtrip(dig_montage, fname_temp)

    # Make a BrainVision file like the one the user would have had
    raw_bv = read_raw_brainvision(bv_fname, preload=True)
    raw_bv_2 = raw_bv.copy()
    mapping = dict()
    for ii, ch_name in enumerate(raw_bv.ch_names):
        mapping[ch_name] = 'EEG%03d' % (ii + 1, )
    raw_bv.rename_channels(mapping)
    for ii, ch_name in enumerate(raw_bv_2.ch_names):
        mapping[ch_name] = 'EEG%03d' % (ii + 33, )
    raw_bv_2.rename_channels(mapping)
    raw_bv.add_channels([raw_bv_2])

    for ii in range(2):
        # Set the montage
        raw_bv.set_montage(dig_montage)

        # Check the result
        evoked = read_evokeds(evoked_fname)[0]

        assert_equal(len(raw_bv.ch_names), len(evoked.ch_names) - 1)
        for ch_py, ch_c in zip(raw_bv.info['chs'], evoked.info['chs'][:-1]):
            assert_equal(ch_py['ch_name'],
                         ch_c['ch_name'].replace('EEG ', 'EEG'))
            # C actually says it's unknown, but it's not (?):
            # assert_equal(ch_py['coord_frame'], ch_c['coord_frame'])
            assert_equal(ch_py['coord_frame'], FIFF.FIFFV_COORD_HEAD)
            c_loc = ch_c['loc'].copy()
            c_loc[c_loc == 0] = np.nan
            assert_allclose(ch_py['loc'], c_loc, atol=1e-7)
        assert_dig_allclose(raw_bv.info, evoked.info)

    # Roundtrip of non-FIF start
    names = ['nasion', 'lpa', 'rpa', '1', '2', '3', '4', '5']
    montage = read_dig_montage(hsp, hpi, elp, names, transform=False)
    pytest.raises(RuntimeError, montage.save, fname_temp)  # must be head coord
    montage = read_dig_montage(hsp, hpi, elp, names)
    _check_roundtrip(montage, fname_temp)

    # Test old way matches new way
    with pytest.deprecated_call():
        dig_montage = read_dig_montage(fif=fif_dig_montage_fname)
    dig_montage_fif = read_dig_fif(fif_dig_montage_fname)
    assert dig_montage.dig == dig_montage_fif.dig
    assert object_diff(dig_montage.ch_names, dig_montage_fif.ch_names) == ''
def test_inst_source():
    """Test DigSource."""
    from mne.gui._file_traits import DigSource
    tempdir = _TempDir()

    inst = DigSource()
    assert inst.inst_fname == '-'

    inst.file = inst_path
    assert inst.inst_dir == op.dirname(inst_path)

    lpa = array([[-7.13766068e-02, 0.00000000e+00, 5.12227416e-09]])
    nasion = array([[3.72529030e-09, 1.02605611e-01, 4.19095159e-09]])
    rpa = array([[7.52676800e-02, 0.00000000e+00, 5.58793545e-09]])
    assert_allclose(inst.lpa, lpa)
    assert_allclose(inst.nasion, nasion)
    assert_allclose(inst.rpa, rpa)

    montage = read_dig_montage(fif=inst_path)  # test reading DigMontage
    montage_path = op.join(tempdir, 'temp_montage.fif')
    montage.save(montage_path)
    inst.file = montage_path
    assert_allclose(inst.lpa, lpa)
    assert_allclose(inst.nasion, nasion)
    assert_allclose(inst.rpa, rpa)
Exemple #5
0
def test_egi_dig_montage():
    """Test EGI MFF XML dig montage support."""
    dig_montage = read_dig_montage(egi=egi_dig_montage_fname, unit='m')

    # # test round-trip IO
    temp_dir = _TempDir()
    fname_temp = op.join(temp_dir, 'egi_test.fif')
    _check_roundtrip(dig_montage, fname_temp)

    # Test coordinate transform
    dig_montage.transform_to_head()
    # nasion
    assert_almost_equal(dig_montage.nasion[0], 0)
    assert_almost_equal(dig_montage.nasion[2], 0)
    # lpa and rpa
    assert_allclose(dig_montage.lpa[1:], 0, atol=1e-16)
    assert_allclose(dig_montage.rpa[1:], 0, atol=1e-16)

    # Test accuracy and embedding within raw object
    raw_egi = read_raw_egi(egi_raw_fname, channel_naming='EEG %03d')
    raw_egi.set_montage(dig_montage)
    test_raw_egi = read_raw_fif(egi_fif_fname)

    assert_equal(len(raw_egi.ch_names), len(test_raw_egi.ch_names))
    for ch_raw, ch_test_raw in zip(raw_egi.info['chs'],
                                   test_raw_egi.info['chs']):
        assert_equal(ch_raw['ch_name'], ch_test_raw['ch_name'])
        assert_equal(ch_raw['coord_frame'], FIFF.FIFFV_COORD_HEAD)
        assert_allclose(ch_raw['loc'], ch_test_raw['loc'], atol=1e-7)
    assert_dig_allclose(raw_egi.info, test_raw_egi.info)
Exemple #6
0
def test_plot_montage():
    """Test plotting montages
    """
    m = read_montage('easycap-M1')
    m.plot()
    m.plot(show_names=True)
    d = read_dig_montage(hsp, hpi, elp, point_names)
    d.plot()
    d.plot(show_names=True)
def test_plot_montage():
    """Test plotting montages
    """
    m = read_montage('easycap-M1')
    m.plot()
    m.plot(show_names=True)
    d = read_dig_montage(hsp, hpi, elp, point_names)
    d.plot()
    d.plot(show_names=True)
Exemple #8
0
def test_plot_montage():
    """Test plotting montages."""
    m = read_montage('easycap-M1')
    m.plot()
    plt.close('all')
    m.plot(kind='3d')
    plt.close('all')
    m.plot(kind='3d', show_names=True)
    plt.close('all')
    m.plot(kind='topomap')
    plt.close('all')
    m.plot(kind='topomap', show_names=True)
    plt.close('all')
    d = read_dig_montage(hsp, hpi, elp, point_names)
    assert '0 channels' in repr(d)
    with pytest.raises(RuntimeError, match='No valid channel positions'):
        d.plot()
    d = read_dig_montage(fif=fif_fname)
    assert '61 channels' in repr(d)
Exemple #9
0
def _check_roundtrip(montage, fname):
    """Check roundtrip writing."""
    assert_equal(montage.coord_frame, 'head')
    montage.save(fname)
    montage_read = read_dig_montage(fif=fname)
    assert_equal(str(montage), str(montage_read))
    for kind in ('elp', 'hsp', 'nasion', 'lpa', 'rpa'):
        if getattr(montage, kind) is not None:
            assert_allclose(getattr(montage, kind),
                            getattr(montage_read, kind), err_msg=kind)
    assert_equal(montage_read.coord_frame, 'head')
Exemple #10
0
def test_read_dig_montage():
    """Test read_dig_montage."""
    names = ['nasion', 'lpa', 'rpa', '1', '2', '3', '4', '5']
    montage = read_dig_montage(hsp, hpi, elp, names, transform=False)
    elp_points = _read_dig_points(elp)
    hsp_points = _read_dig_points(hsp)
    hpi_points = read_mrk(hpi)
    assert_equal(montage.point_names, names)
    assert_array_equal(montage.elp, elp_points)
    assert_array_equal(montage.hsp, hsp_points)
    assert_array_equal(montage.hpi, hpi_points)
    assert (montage.dev_head_t is None)
    montage = read_dig_montage(hsp, hpi, elp, names,
                               transform=True, dev_head_t=True)
    # check coordinate transformation
    # nasion
    assert_almost_equal(montage.nasion[0], 0)
    assert_almost_equal(montage.nasion[2], 0)
    # lpa and rpa
    assert_allclose(montage.lpa[1:], 0, atol=1e-16)
    assert_allclose(montage.rpa[1:], 0, atol=1e-16)
    # device head transform
    dev_head_t = fit_matched_points(tgt_pts=montage.elp,
                                    src_pts=montage.hpi, out='trans')
    assert_array_equal(montage.dev_head_t, dev_head_t)

    # Digitizer as array
    m2 = read_dig_montage(hsp_points, hpi_points, elp_points, names, unit='m')
    assert_array_equal(m2.hsp, montage.hsp)
    m3 = read_dig_montage(hsp_points * 1000, hpi_points, elp_points * 1000,
                          names)
    assert_allclose(m3.hsp, montage.hsp)

    # test unit parameter and .mat support
    tempdir = _TempDir()
    mat_hsp = op.join(tempdir, 'test.mat')
    savemat(mat_hsp, dict(Points=(1000 * hsp_points).T), oned_as='row')
    montage_cm = read_dig_montage(mat_hsp, hpi, elp, names, unit='cm')
    assert_allclose(montage_cm.hsp, montage.hsp * 10.)
    assert_allclose(montage_cm.elp, montage.elp * 10.)
    assert_array_equal(montage_cm.hpi, montage.hpi)
    pytest.raises(ValueError, read_dig_montage, hsp, hpi, elp, names,
                  unit='km')
    # extra columns
    extra_hsp = op.join(tempdir, 'test.txt')
    with open(hsp, 'rb') as fin:
        with open(extra_hsp, 'wb') as fout:
            for line in fin:
                if line.startswith(b'%'):
                    fout.write(line)
                else:
                    # extra column
                    fout.write(line.rstrip() + b' 0.0 0.0 0.0\n')
    with pytest.warns(RuntimeWarning, match='Found .* columns instead of 3'):
        montage_extra = read_dig_montage(extra_hsp, hpi, elp, names)
    assert_allclose(montage_extra.hsp, montage.hsp)
    assert_allclose(montage_extra.elp, montage.elp)
Exemple #11
0
def test_plot_montage():
    """Test plotting montages."""
    import matplotlib.pyplot as plt
    m = read_montage('easycap-M1')
    m.plot()
    plt.close('all')
    m.plot(kind='3d')
    plt.close('all')
    m.plot(kind='3d', show_names=True)
    plt.close('all')
    m.plot(kind='topomap')
    plt.close('all')
    m.plot(kind='topomap', show_names=True)
    plt.close('all')
    d = read_dig_montage(hsp, hpi, elp, point_names)
    d.plot()
    plt.close('all')
    d.plot(kind='3d')
    plt.close('all')
    d.plot(kind='3d', show_names=True)
    plt.close('all')
import sys
from mne.channels import read_dig_montage
from mne.io import read_raw_egi


# Command Line Arguments
# 1. The path to the EGI simple binary (.raw) file
# 2. The path to the corresponding coordinates (.xml) file
# 3. The output path to where you'd like to write the fif file
# Note that the output fif file should end with _raw.fif to keep with MNE
# convetion

# Example of usage:
# python convert_egi_raw.py ./egi_raw/test_data.raw ./coordinates/
# test_data_coordinates.xml ./fif_raw/test_raw.fif
arguments = sys.argv
raw_input_path = arguments[1]
coordinates_path = arguments[2]
raw_output_path = arguments[3]

raw = read_raw_egi(raw_input_path, misc=['EEG 257'])
dig_montage = read_dig_montage(egi=coordinates_path)
raw.set_montage(dig_montage)

raw.save(raw_output_path)
Exemple #13
0
def bv2fif(dataf,
           corf,
           ch_order=None,
           aux=('VEOG', 'HEOG', 'ECG', 'EMG'),
           preload='default',
           ref_ch='Fp1',
           dbs=False,
           use_find_events='dbs',
           tmin=-2,
           tmax=2,
           baseline=(-0.5, -0.1),
           detrend=1):
    """Function to convert .eeg, .vmrk and .vhdr BrainVision files to a 
       combined .fif format file.
    Parameters
    ----------
    dataf : str
        The .vhdr file that contains references to the data
    corf : str
        The COR.fif file that contains the montage for this
        particular subject. This will be generated through
        mne_analyze, possibly while using the TMS-EEG GUI.
    ch_order : list of str | None
        If not 'None', a custom channel order is used.
    aux : tuple 
        Auxillary/accessory electrodes to be included in the data.
    preload : 'default' | False
        If false, load data into RAM, if true memory map to disk
    ref_ch : str
        Reference channel used
    dbs: bool
        If true stim channels are named 'DBS' and use_find_events
        is true by default.
    use_find_events : bool | 'dbs'
        If true or 'dbs' and dbs is true, then the peak amplitude
        will be used to find stimulus markers.
    tmin: float
        Time when epochs start
    tmax: float
        Time when epochs end
    baseline: tuple (float, float) | None
        Time to use for baseline mean subtraction
    detrend: int
        1 for linear detrend, 0 for mean subtraction and None for nothing
    Notes
    -----
    An older version of MNE contained a bug that prevented adding 
    channels while using memory mapping. A script to circumvent 
    this also exists.
    """
    use_find_events = ((dbs and use_find_events == 'dbs') or
                       (isinstance(use_find_events, bool) and use_find_events))
    if preload == 'default':
        preload = os.path.dirname(dataf) + '/workfile'
    #
    raw = read_raw_brainvision(dataf, preload=preload)
    if corf is None:
        montage = None
    elif '.bvct' in op.basename(corf):
        montage = read_dig_montage(bvct=corf)
    elif '.csv' in op.basename(corf):
        montage = read_dig_montage(csv=corf)
    else:
        raise ValueError('corf not understood')
    #
    if ch_order is None:
        if all([ch in ch_name_order for ch in raw.ch_names]):
            order_dict = {ch: ch_name_order.index(ch) for ch in raw.ch_names}
            ch_order = sorted(order_dict, key=order_dict.get)
        else:  # if no channel order is given and we get names we didn't expect, just sort the channels
            ch_order = sorted(inst.ch_names)
    #
    if use_find_events:
        event_ch = get_events(raw)
        old_event_ch = [ch for ch in raw.info['ch_names'] if 'STI' in ch]
        if old_event_ch:
            raw.drop_channels([old_event_ch[0]])
        raw.add_channels([event_ch])
        if use_find_events and use_find_events != 'dbs':
            raw.rename_channels({'DBS': 'TMS'})
    else:
        events, event_ids = events_from_annotations(raw)
    #
    prepInst(raw, dataf, 'raw', montage, ref_ch, aux, 'DBS' if dbs else 'TMS',
             ch_order)
Exemple #14
0
 def save_setup(self):
     de = self.data_entries.copy()
     raw_fname = de.pop('New File').get()
     loc_fname = de.pop('Loc File').get()
     suffix = raw_fname.split('.')[-1]
     if suffix == 'fif':
         try:
             raw = Raw(raw_fname, preload=False)
         except Exception as e:
             print(e)
             messagebox.showerror('Error', 'Failed to read fif')
             return
         if loc_fname:
             messagebox.showwarning('Warning',
                                    'Ignoring location file given')
     elif suffix == 'vhdr':
         if not loc_fname:
             messagebox.showerror('Error', 'Location file not specified')
         try:
             raw = read_raw_brainvision(raw_fname,
                                        preload=os.path.join(
                                            self.sub_dirs['tmp'],
                                            'raw_tmp'))
         except Exception as e:
             print(e)
             messagebox.showerror('Error',
                                  'Failed to read BrainVision raw file')
             return
         try:
             montage = read_dig_montage(bvct=loc_fname)
             ref_name = [
                 ch for ch in montage.dig_ch_pos
                 if not ch in raw.info['ch_names']
             ]
             if len(ref_name) != 1:
                 ref_name = simpledialog.askstring(
                     'Reference Channel',
                     'What is the reference channel name?',
                     parent=self.root)
             else:
                 ref_name = ref_name[0]
             info = create_info([ref_name], raw.info['sfreq'], ['eeg'])
             ref = RawArray(np.zeros((1, len(raw.times))), info)
             ref.info['lowpass'] = raw.info['lowpass']
             raw = raw.add_channels([ref])  #, force_update_info=True)
             #
             for ch_type in ['eog', 'ecg', 'emg', 'stim']:
                 chs = [
                     ch for ch in raw.info['ch_names']
                     if ch_type in ch.lower()
                 ]
                 for ch in chs:
                     ch_ix = raw.ch_names.index(ch)
                     raw._data[ch_ix, :] *= 1e-6
                     raw.set_channel_types({ch: ch_type})
             raw = raw.set_montage(montage, verbose=False)
         except Exception as e:
             print(e)
             messagebox.showerror(
                 'Error', 'Failed to read BrainVision location file')
             return
     else:
         messagebox.showerror('Error', 'Unrecognized raw file format')
         return
     self.save_exp(raw)
Exemple #15
0
    hpi = list()
    idx = 0
    for this_hpi in epochs.info['hpi_results'][idx]['dig_points']:
        if this_hpi['kind'] == 1 or this_hpi['kind'] == 2:
            hpi.append(this_hpi['r'])
    hpi = np.array(hpi)
    # read hpi_mri.txt (hpi position in MRI coord from brainsight)
    hpi_fname = op.join(neuronav_path, 'hpi_mri_surf.txt')
    landmark = read_hpi_mri(hpi_fname)
    point_names = ['NEC', 'LEC', 'REC']  # Nasion, Left and Right electrodes
    elp = np.array([landmark[key] for key in point_names])
    # Set montage
    dig_montage = read_dig_montage(hsp=None,
                                   hpi=hpi,
                                   elp=elp,
                                   point_names=point_names,
                                   unit='mm',
                                   transform=False,
                                   dev_head_t=True)
    epochs.set_montage(dig_montage)
    # # Visually check the montage
    # plot_trans(epochs.info, trans=None, subject=freesurf_subject, dig=True,
    #            meg_sensors=True, subjects_dir=subjects_dir, brain=True)

    # Create or Read forward model
    fwd_fname = op.join(subject_path, '%s-fwd.fif' % subject)
    if not op.isfile(fwd_fname):
        bem_dir = op.join(freesurf_subject_path, 'bem')
        bem_sol_fname = op.join(bem_dir,
                                freesurf_subject + '-5120-bem-sol.fif')
        src_fname = op.join(bem_dir, freesurf_subject + '-oct-6-src.fif')
Exemple #16
0
def bv2fif(dataf,
           corf,
           ch_order=None,
           eogs=('VEOG', 'HEOG'),
           ecg='ECG',
           emg='EMG',
           preload='default',
           ref_ch='Fp1',
           dbs=False,
           new_sfreq=1000.0):
    montage = read_dig_montage(bvct=corf)
    if preload == 'default':
        preload = os.path.dirname(dataf) + '/workfile'

    raw = read_raw_brainvision(dataf, preload=preload)

    if dbs:
        event_ch = get_events(raw)

    # save downsampled raw for multitaper spectrogram
    raw_data = np.zeros(
        (raw._data.shape[0],
         int(raw._data.shape[1] / raw.info['sfreq'] * new_sfreq)))
    raw_info = raw.info.copy()
    raw_info['sfreq'] = new_sfreq
    for i in tqdm(range(len(raw._data))):
        ch = raw._data[i, ::int(raw.info['sfreq'] / new_sfreq)]
        raw_data[i] = ch
        del ch

    raw_resampled = RawArray(raw_data, raw_info)
    raw_resampled.annotations = raw.annotations

    if dbs:
        old_event_ch = [ch for ch in raw.info['ch_names'] if 'STI' in ch]
        if old_event_ch:
            raw_resampled.drop_channels([old_event_ch[0]])
        event_ch._data = event_ch._data[:, ::int(raw.info['sfreq'] /
                                                 new_sfreq)]
        event_ch.info['sfreq'] = new_sfreq
        event_ch.__len__ = len(event_ch._data[0])
        event_ch.info['lowpass'] = raw_resampled.info['lowpass']
        raw_resampled.add_channels([event_ch])

    prepInst(raw_resampled, dataf, 'raw', montage, ref_ch, eogs, ecg, emg)

    events, event_ids = events_from_annotations(raw)
    if len(np.unique(events[:, 2])) > 1:
        events = events[np.where(events[:,
                                        2] == events[1,
                                                     2])[0]]  #skip new segment
    epochs = Epochs(raw,
                    events,
                    tmin=-2,
                    tmax=2,
                    proj=False,
                    preload=op.dirname(dataf) + '/workfile-epo',
                    baseline=(-0.5, -0.1),
                    verbose=False,
                    detrend=1)
    events = events[
        epochs.
        selection]  #in case any epochs don't have data and get thrown out (poorly placed at beginning or end)
    epo_data = np.zeros(
        (epochs._data.shape[0], epochs._data.shape[1],
         int(np.ceil(epochs._data.shape[2] / epochs.info['sfreq'] *
                     new_sfreq))))
    for i in tqdm(range(epochs._data.shape[0])):
        for j in range(epochs._data.shape[1]):
            epo_curr = epochs._data[i,
                                    j, ::int(epochs.info['sfreq'] / new_sfreq)]
            epo_data[i, j] = epo_curr
            del epo_curr
    events[:, 0] = np.array(events[:, 0] * new_sfreq / raw.info['sfreq'],
                            dtype=int)
    epo_resampled = EpochsArray(epo_data, epochs.info.copy(), events, tmin=-2)
    epo_resampled.info['sfreq'] = new_sfreq
    epo_resampled.events[:, 2] = np.arange(len(events))
    epo_resampled.event_id = {str(i): i for i in range(len(events))}

    prepInst(epo_resampled, dataf, 'epo', montage, ref_ch, eogs, ecg, emg)
Exemple #17
0
    def save_setup(self):
        de = self.data_entries.copy()
        raw_fname = de.pop('Load New File').get()
        loc_fname = de.pop('Load Location File').get()
        suffix = raw_fname.split('.')[-1]
        if suffix == 'fif':
            try:
                raw = Raw(raw_fname,preload=False)
            except Exception as e:
                print(e)
                messagebox.showerror('Error','Failed to read fif')
                return
            if loc_fname:
                messagebox.showwarning('Warning','Ignoring location file given')
        elif suffix == 'vhdr':
            if not loc_fname:
               messagebox.showerror('Error','Location file not specified')
            try:
                raw = read_raw_brainvision(raw_fname,
                    preload=op.join(self.sub_dirs['tmp'],'raw_tmp'))
            except Exception as e:
                print(e)
                messagebox.showerror('Error','Failed to read BrainVision raw file')
                return
            try:
                montage = read_dig_montage(bvct=loc_fname)
                ref_name = [ch for ch in montage.dig_ch_pos if not
                            ch in raw.info['ch_names']]
                if len(ref_name) != 1:
                    ref_name = simpledialog.askstring('Reference Channel',
                                                      'What is the reference channel name?',
                                                      parent=self.root)
                else:
                    ref_name = ref_name[0]
                info = create_info([ref_name], raw.info['sfreq'], ['eeg'])
                ref = RawArray(np.zeros((1, len(raw.times))), info)
                ref.info['lowpass'] = raw.info['lowpass']
                raw = raw.add_channels([ref]) #, force_update_info=True)
                #
                for ch_type in ['eog','ecg','emg','stim']:
                    chs = [ch for ch in raw.info['ch_names']
                           if ch_type in ch.lower()]
                    for ch in chs:
                        ch_ix = raw.ch_names.index(ch)
                        raw._data[ch_ix, :] *= 1e-6
                        raw.set_channel_types({ch:ch_type})
                raw = raw.set_montage(montage,verbose=False)
            except Exception as e:
                print(e)
                messagebox.showerror('Error','Failed to read BrainVision location file')
                return
        else:
            messagebox.showerror('Error','Unrecognized raw file format')
            return
        self.save_exp(raw)
        transf = self.data_entries['Coord Trans fname'].get() 
        if not op.isfile(transf):
            subject = self.data_entries['Subject'].get()
            os.environ['SUBJECT'] = subject
            fs_dir = self.data_entries['FS Dir'].get()
            os.environ['SUBJECTS_DIR'] = fs_dir
            messagebox.showinfo(
                'Coregistration','In this next interactive GUI, will need to\n' +
                '1. Load the pial surface file -> Load Surface -> Select Pial Surface\n' +
                '2. Load the subject\'s digitization data: File -> Load digitizer data ->' +
                ' Select the raw data file for this session\n' + 
                '3. Open the coordinate alignment window: Adjust -> Coordinate Alignment\n' + 
                '4. Open the viewer window: View -> Show viewer\n' +
                '5. In the coordinate alignment window, click RAP, LAP and Naision, ' + 
                'and then after clicking each of those click on the corresponing ' +
                'fiducial points on the reconstructed head model\n' +
                '6. Click align using fiducials\n' +
                '7. In the View window: select Options -> Show digitizer data\n'
                '8. Adjust the x, y and z coordinates and rotation until ' +
                'the alignment is as close to the ground truth as possible\n' +
                'If you don\'t know these instructions, feel free to copy and paste')

            self.output_to_terminal('mne_analyze')
Exemple #18
0
def test_read_dig_montage():
    """Test read_dig_montage."""
    names = ['nasion', 'lpa', 'rpa', '1', '2', '3', '4', '5']
    montage = read_dig_montage(hsp, hpi, elp, names, transform=False)
    elp_points = _read_dig_points(elp)
    hsp_points = _read_dig_points(hsp)
    hpi_points = read_mrk(hpi)
    with pytest.deprecated_call():
        assert_equal(montage.point_names, names)
        assert_array_equal(montage.elp, elp_points)
        assert_array_equal(montage.hsp, hsp_points)
    assert (montage.dev_head_t is None)
    montage = read_dig_montage(hsp,
                               hpi,
                               elp,
                               names,
                               transform=True,
                               dev_head_t=True)
    # check coordinate transformation
    # nasion
    with pytest.deprecated_call():
        assert_almost_equal(montage.nasion[0], 0)
        assert_almost_equal(montage.nasion[2], 0)
    # lpa and rpa
    with pytest.deprecated_call():
        assert_allclose(montage.lpa[1:], 0, atol=1e-16)
        assert_allclose(montage.rpa[1:], 0, atol=1e-16)
    # device head transform

    EXPECTED_DEV_HEAD_T = np.array(
        [[-3.72201691e-02, -9.98212167e-01, -4.67667497e-02, -7.31583414e-04],
         [8.98064989e-01, -5.39382685e-02, 4.36543170e-01, 1.60134431e-02],
         [-4.38285221e-01, -2.57513699e-02, 8.98466990e-01, 6.13035748e-02],
         [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]])
    assert_allclose(montage.dev_head_t, EXPECTED_DEV_HEAD_T, atol=1e-7)

    # Digitizer as array
    with pytest.deprecated_call():
        m2 = read_dig_montage(hsp_points,
                              hpi_points,
                              elp_points,
                              names,
                              unit='m')
        assert_array_equal(m2.hsp, montage.hsp)
        m3 = read_dig_montage(hsp_points * 1000, hpi_points, elp_points * 1000,
                              names)
    with pytest.deprecated_call():
        assert_allclose(m3.hsp, montage.hsp)

    # test unit parameter and .mat support
    tempdir = _TempDir()
    mat_hsp = op.join(tempdir, 'test.mat')
    savemat(mat_hsp, dict(Points=(1000 * hsp_points).T), oned_as='row')
    montage_cm = read_dig_montage(mat_hsp, hpi, elp, names, unit='cm')
    with pytest.deprecated_call():
        assert_allclose(montage_cm.hsp, montage.hsp * 10.)
        assert_allclose(montage_cm.elp, montage.elp * 10.)
    pytest.raises(ValueError,
                  read_dig_montage,
                  hsp,
                  hpi,
                  elp,
                  names,
                  unit='km')
    # extra columns
    extra_hsp = op.join(tempdir, 'test.txt')
    with open(hsp, 'rb') as fin:
        with open(extra_hsp, 'wb') as fout:
            for line in fin:
                if line.startswith(b'%'):
                    fout.write(line)
                else:
                    # extra column
                    fout.write(line.rstrip() + b' 0.0 0.0 0.0\n')
    with pytest.warns(RuntimeWarning, match='Found .* columns instead of 3'):
        montage_extra = read_dig_montage(extra_hsp, hpi, elp, names)
    with pytest.deprecated_call():
        assert_allclose(montage_extra.hsp, montage.hsp)
        assert_allclose(montage_extra.elp, montage.elp)