def test_read_write_info(): data_dir = _get_test_data_dir() raw = create_fake_raw(n_channels=4, n_samples=5, sfreq=25.) raw.set_channel_types({'a': 'eeg', 'b': 'ecog', 'c': 'eeg', 'd': 'ecog'}) fname = op.join(data_dir, 'temp_info.hdf5') if op.isfile(fname): os.remove(op.join(data_dir, fname)) write_info(fname, raw.info) info = read_info(fname) compare_info(info, raw.info) raw = mne.io.read_raw_fif(op.join(data_dir, 'rest_sample_data-raw.fif')) write_info(fname, raw.info, overwrite=True) info = read_info(fname) compare_info(info, raw.info)
find_range) from borsar.cluster import Clusters, read_cluster from borsar.cluster.checks import (_clusters_safety_checks, _check_description, _clusters_chan_vert_checks, _check_dimnames_kwargs) from borsar.cluster.utils import (_check_stc, _label_from_cluster, _get_clim, _prepare_cluster_description, _handle_dims, _aggregate_cluster, _get_units, _get_dimcoords, _get_mass_range, _format_cluster_pvalues, _index_from_dim, _full_dimname, _human_readable_dimlabel) from borsar.cluster.viz import _label_axis, _move_axes_to # setup download_test_data() data_dir = _get_test_data_dir() fwd_fname = 'DiamSar-eeg-oct-6-fwd.fif' fwd = mne.read_forward_solution(op.join(data_dir, fwd_fname)) def _create_random_clusters(dims='ch_tm', n_clusters=1): n_channels, n_times, n_freqs = 15, 35, 15 try: # mne > 0.18 mntg = mne.channels.make_standard_montage('standard_1020') except AttributeError: # mne 0.18 and below mntg = mne.channels.read_montage('standard_1020') ch_names = mntg.ch_names[slice(0, 89, 6)]
def test_psd_class(): mne_version = version.parse(mne.__version__) # get data data_dir = _get_test_data_dir() download_test_data() # read data raw_fname = op.join(data_dir, 'DiamSar_023_rest_raw.fif') raw = mne.io.read_raw_fif(raw_fname, preload=True) # compute psd event_id = {'S 11': 11} events, _ = mne.events_from_annotations(raw, event_id=event_id) psd = compute_psd(raw, tmin=0.5, tmax=20.5, winlen=2., step=0.5, events=events, event_id=[11]) # make sure plotting does not error if mne_version > version.parse('0.18'): psd.plot(dB=False, fmax=40, show=False) psd.plot(fmax=40, average=True, show=False) else: with pytest.raises(ImportError): psd.plot(dB=False, fmax=40, show=False) topo = psd.plot_topomap(freqs=[11], show=False) assert isinstance(topo.axes, plt.Axes) topo = psd.plot_topomap(freqs=[6, 11], show=False) assert len(topo.axes) == 2 topo = psd.plot_topomap(freqs=[8, 10, 12], show=False) assert len(topo.axes) == 3 plt.close('all') # data shape checks assert len(psd.ch_names) == len(raw.ch_names) assert psd.data.shape[-1] == len(psd.freqs) assert psd.data.shape[-2] == len(raw.ch_names) psd_orig = psd.copy() psd2 = psd.average() assert (psd.data == psd2.data).all() psd.crop(fmin=10, fmax=15) assert (psd.freqs[0] - 10) < 0.5 assert (psd.freqs[-1] - 15) < 0.5 # test for (deep)copy psd2 = psd.copy() psd2.data[0, 0] = 23 assert not (psd._data[0, 0] == 23) # test to_evoked psd2 = psd_orig.copy().average() evoked = psd_orig.to_evoked() assert isinstance(evoked, mne.Evoked) assert (evoked.data == psd2.data).all() # test plot_joint() psd_orig.plot_joint() plt.close('all') # psd with Epochs # --------------- epochs = mne.Epochs(raw, events, event_id, tmin=0., tmax=23., baseline=None, preload=True) psd_epo = compute_psd(epochs, tmin=0.5, tmax=20.5, winlen=2., step=0.5, events=events, event_id=[11]) if mne_version > version.parse('0.18'): psd_epo.plot(show=False) psd_avg = psd_epo.copy().average() assert psd_epo.data.ndim == 3 assert psd_avg.data.ndim == 2 arr = np.random.randn(23, 48) with pytest.raises(TypeError, match='works only with Raw or Epochs'): psd_epo = compute_psd(arr, tmin=0.5, tmax=20.5, winlen=2., step=0.5, events=events, event_id=[11]) # psd construction with pytest.raises(ValueError, match='has to be 3d'): use_data = psd_epo.data[..., np.newaxis] psd = PSD(use_data, psd_epo.freqs, raw.info) with pytest.raises(ValueError, match='or 2d'): use_data = psd_epo.data[0, :, 0] psd = PSD(use_data, psd_epo.freqs, raw.info) # test for __repr__ psd_epo2 = psd_epo.copy().crop(fmin=8, fmax=12) rpr = '<borsar.freq.PSD (2 epochs, 64 channels, 9 frequencies), 8 - 12 Hz>' assert str(psd_epo2) == rpr # test chaining psd_epo3 = psd_epo.copy().crop(fmin=8, fmax=12).average() rpr = '<borsar.freq.PSD (64 channels, 9 frequencies), 8 - 12 Hz>' assert str(psd_epo3) == rpr # test channel picking psd2 = psd_epo.copy().pick_channels(['Fz', 'Pz']) assert psd2.data.shape[1] == 2 # missing: # compute_rest_psd when events is None # Epochs with metadata # -------------------- # read data epochs_fname = op.join(data_dir, 'GabCon-48_epo.fif') epochs = mne.read_epochs(epochs_fname, preload=True) assert epochs.metadata is not None psd = compute_psd(epochs, tmin=0.5, tmax=1.) assert psd.data.ndim == 3 assert psd.data.shape[0] == epochs._data.shape[0] psd_slow = psd['RT > 0.65'] epochs_slow = epochs['RT > 0.65'] # TODO: later use len(psd_slow) here assert len(epochs_slow) == psd_slow.data.shape[0]
def test_cluster_based_regression(): np.random.seed(23) data_dir = _get_test_data_dir() # TEST 1 # ====== # read data and fieldtrip's stat results stat = loadmat(op.join(data_dir, 'ft_stat_test_01.mat'), squeeze_me=True)['stat'] all_data = loadmat(op.join(data_dir, 'cluster_regr_test_01.mat'), squeeze_me=True) data = all_data['data'] pred = all_data['pred'] t_values, clusters, cluster_p, distrib = cluster_based_regression( data, pred, return_distribution=True, progressbar=False) # cluster p values should be very similar # --------------------------------------- cluster_p_ft = np.concatenate([ stat['posclusters'].item()['prob'], [stat['negclusters'].item()['prob'].item()] ]).astype('float') # for small p-values the differences should be smaller, # for large they could reach up to 0.095 assert (np.abs(cluster_p_ft - cluster_p) < [0.01, 0.095, 0.11]).all() # distributions should be very similar # ------------------------------------ distrib_ft = { prefix: stat['{}distribution'.format(prefix)].item() for prefix in ['pos', 'neg'] } vals = np.array([5., 15, 30, 50, 100]) max_perc_error = np.array([7, 7, 5, 5, 4.5]) / 100. for fun, prefix, vls in zip([np.less, np.greater], ['pos', 'neg'], [vals, vals * -1]): ft = np.array([fun(distrib_ft[prefix], v).mean() for v in vls]) brsr = np.array([fun(distrib[prefix], v).mean() for v in vls]) assert (np.abs(ft - brsr) < max_perc_error).all() # masks should be the same # ------------------------ posmat = stat['posclusterslabelmat'].item() negmat = stat['negclusterslabelmat'].item() assert ((posmat == 1) == clusters[0]).all() assert ((posmat == 2) == clusters[1]).all() assert ((negmat == 1) == clusters[2]).all() # t values should be almost the same # ---------------------------------- np.testing.assert_allclose(stat['stat'].item(), t_values, rtol=1e-10) # TEST 2 # ====== # smoke test for running cluster_based_regression with adjacency data = np.random.random((15, 4, 4)) preds = np.random.random(15) T, F = True, False adjacency = sparse.coo_matrix([[F, T, T, F], [T, F, T, F], [T, T, F, T], [F, F, T, F]]) tvals, clst, clst_p = cluster_based_regression(data, preds, adjacency=adjacency)