def test_first_level_design_creation(): # Test processing of FMRI inputs with InTemporaryDirectory(): shapes = ((7, 8, 9, 10), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) # basic test based on basic_paradigm and glover hrf t_r = 10.0 slice_time_ref = 0. events = basic_paradigm() model = FirstLevelModel(t_r, slice_time_ref, mask_img=mask, drift_model='polynomial', drift_order=3) model = model.fit(func_img, events) frame1, X1, names1 = check_design_matrix(model.design_matrices_[0]) # check design computation is identical n_scans = get_data(func_img).shape[3] start_time = slice_time_ref * t_r end_time = (n_scans - 1 + slice_time_ref) * t_r frame_times = np.linspace(start_time, end_time, n_scans) design = make_first_level_design_matrix(frame_times, events, drift_model='polynomial', drift_order=3) frame2, X2, names2 = check_design_matrix(design) assert_array_equal(frame1, frame2) assert_array_equal(X1, X2) assert_array_equal(names1, names2) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del FUNCFILE, mask, model, func_img
def test_high_level_non_parametric_inference_with_paths(): with InTemporaryDirectory(): n_perm = 100 shapes = ((7, 8, 9, 1), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) c1 = np.eye(len(X.columns))[0] neg_log_pvals_img = non_parametric_inference(Y, design_matrix=X, second_level_contrast=c1, mask=mask, n_perm=n_perm) neg_log_pvals = get_data(neg_log_pvals_img) assert isinstance(neg_log_pvals_img, Nifti1Image) assert_array_equal(neg_log_pvals_img.affine, load(mask).affine) assert np.all(neg_log_pvals <= -np.log10(1.0 / (n_perm + 1))) assert np.all(0 <= neg_log_pvals) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory del X, Y, FUNCFILE, func_img, neg_log_pvals_img
def test_flm_reporting(use_method): with InTemporaryDirectory(): shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 16)), 3 mask, fmri_data, design_matrices = write_fake_fmri_data_and_design(shapes, rk) flm = FirstLevelModel(mask_img=mask).fit( fmri_data, design_matrices=design_matrices) contrast = np.eye(3)[1] if use_method: report_flm = flm.generate_report( contrast, plot_type='glass', height_control=None, min_distance=15, alpha=0.001, threshold=2.78) else: report_flm = glmr.make_glm_report(flm, contrast, plot_type='glass', height_control=None, min_distance=15, alpha=0.001, threshold=2.78, ) ''' catches & raises UnicodeEncodeError in HTMLDocument.get_iframe() Python2's limited unicode support causes HTMLDocument.get_iframe() to mishandle certain unicode characters, like the greek alpha symbol and raises this error. Calling HTMLDocument.get_iframe() here causes the tests to fail on Python2, alerting us if such a situation arises due to future modifications. ''' report_iframe = report_flm.get_iframe() # So flake8 doesn't complain about not using variable (F841) report_iframe del mask, flm, fmri_data
def test_masking_first_level_model(): """ Checks that using NiftiMasker when instantiating FirstLevelModel doesn't raise Error when calling generate_report(). """ with InTemporaryDirectory(): shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 16)), 3 mask, fmri_data, design_matrices =\ write_fake_fmri_data_and_design(shapes, rk) masker = NiftiMasker(mask_img=mask) masker.fit(fmri_data) flm = FirstLevelModel(mask_img=masker).fit( fmri_data, design_matrices=design_matrices ) contrast = np.eye(3)[1] report_flm = flm.generate_report( contrast, plot_type='glass', height_control=None, min_distance=15, alpha=0.001, threshold=2.78 ) report_iframe = report_flm.get_iframe() # So flake8 doesn't complain about not using variable (F841) report_iframe del mask, flm, fmri_data, masker
def test_first_level_contrast_computation(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 10),) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) # basic test based on basic_paradigm and glover hrf t_r = 10.0 slice_time_ref = 0. events = basic_paradigm() # Ordinary Least Squares case model = FirstLevelModel(t_r, slice_time_ref, mask_img=mask, drift_model='polynomial', drift_order=3, minimize_memory=False) c1, c2, cnull = np.eye(7)[0], np.eye(7)[1], np.zeros(7) # asking for contrast before model fit gives error with pytest.raises(ValueError): model.compute_contrast(c1) # fit model model = model.fit([func_img, func_img], [events, events]) # Check that an error is raised for invalid contrast_def with pytest.raises(ValueError, match="contrast_def must be an array or str or list"): model.compute_contrast(37) # smoke test for different contrasts in fixed effects model.compute_contrast([c1, c2]) # smoke test for same contrast in fixed effects model.compute_contrast([c2, c2]) # smoke test for contrast that will be repeated model.compute_contrast(c2) model.compute_contrast(c2, 'F') model.compute_contrast(c2, 't', 'z_score') model.compute_contrast(c2, 't', 'stat') model.compute_contrast(c2, 't', 'p_value') model.compute_contrast(c2, None, 'effect_size') model.compute_contrast(c2, None, 'effect_variance') # formula should work (passing varible name directly) model.compute_contrast('c0') model.compute_contrast('c1') model.compute_contrast('c2') # smoke test for one null contrast in group model.compute_contrast([c2, cnull]) # only passing null contrasts should give back a value error with pytest.raises(ValueError): model.compute_contrast(cnull) with pytest.raises(ValueError): model.compute_contrast([cnull, cnull]) # passing wrong parameters with pytest.raises(ValueError): model.compute_contrast([]) with pytest.raises(ValueError): model.compute_contrast([c1, []]) with pytest.raises(ValueError): model.compute_contrast(c1, '', '') with pytest.raises(ValueError): model.compute_contrast(c1, '', []) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del func_img, FUNCFILE, model
def test_explicit_fixed_effects(): """ tests the fixed effects performed manually/explicitly""" with InTemporaryDirectory(): shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 16)), 3 mask, fmri_data, design_matrices = write_fake_fmri_data_and_design( shapes, rk) contrast = np.eye(rk)[1] # session 1 multi_session_model = FirstLevelModel(mask_img=mask).fit( fmri_data[0], design_matrices=design_matrices[:1]) dic1 = multi_session_model.compute_contrast(contrast, output_type='all') # session 2 multi_session_model.fit(fmri_data[1], design_matrices=design_matrices[1:]) dic2 = multi_session_model.compute_contrast(contrast, output_type='all') # fixed effects model multi_session_model.fit(fmri_data, design_matrices=design_matrices) fixed_fx_dic = multi_session_model.compute_contrast(contrast, output_type='all') # manual version contrasts = [dic1['effect_size'], dic2['effect_size']] variance = [dic1['effect_variance'], dic2['effect_variance']] ( fixed_fx_contrast, fixed_fx_variance, fixed_fx_stat, ) = compute_fixed_effects(contrasts, variance, mask) assert_almost_equal(fixed_fx_contrast.get_data(), fixed_fx_dic['effect_size'].get_data()) assert_almost_equal(fixed_fx_variance.get_data(), fixed_fx_dic['effect_variance'].get_data()) assert_almost_equal(fixed_fx_stat.get_data(), fixed_fx_dic['stat'].get_data()) # test without mask variable ( fixed_fx_contrast, fixed_fx_variance, fixed_fx_stat, ) = compute_fixed_effects(contrasts, variance) assert_almost_equal(fixed_fx_contrast.get_data(), fixed_fx_dic['effect_size'].get_data()) assert_almost_equal(fixed_fx_variance.get_data(), fixed_fx_dic['effect_variance'].get_data()) assert_almost_equal(fixed_fx_stat.get_data(), fixed_fx_dic['stat'].get_data()) # ensure that using unbalanced effects size and variance images # raises an error with pytest.raises(ValueError): compute_fixed_effects(contrasts * 2, variance, mask) del mask, multi_session_model
def test_high_level_glm_with_paths(): shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 14)), 3 with InTemporaryDirectory(): mask_file, fmri_files, design_files = write_fake_fmri_data_and_design(shapes, rk) multi_session_model = FirstLevelModel(mask_img=None).fit( fmri_files, design_matrices=design_files) z_image = multi_session_model.compute_contrast(np.eye(rk)[1]) assert_array_equal(z_image.affine, load(mask_file).affine) assert get_data(z_image).std() < 3. # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del z_image, fmri_files, multi_session_model
def test_fmri_inputs(): # Test processing of FMRI inputs with InTemporaryDirectory(): shapes = ((7, 8, 9, 10), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) T = func_img.shape[-1] conf = pd.DataFrame([0, 0]) des = pd.DataFrame(np.ones((T, 1)), columns=['']) des_fname = 'design.csv' des.to_csv(des_fname) for fi in func_img, FUNCFILE: for d in des, des_fname: FirstLevelModel().fit(fi, design_matrices=d) FirstLevelModel(mask_img=None).fit([fi], design_matrices=d) FirstLevelModel(mask_img=mask).fit(fi, design_matrices=[d]) FirstLevelModel(mask_img=mask).fit([fi], design_matrices=[d]) # test with confounds FirstLevelModel(mask_img=mask).fit([fi], design_matrices=[d], confounds=conf) # test with confounds as numpy array FirstLevelModel(mask_img=mask).fit([fi], design_matrices=[d], confounds=conf.values) FirstLevelModel(mask_img=mask).fit([fi, fi], design_matrices=[d, d]) FirstLevelModel(mask_img=None).fit((fi, fi), design_matrices=(d, d)) with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit([fi, fi], d) with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit(fi, [d, d]) # At least paradigms or design have to be given with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit(fi) # If paradigms are given then both tr and slice time ref were # required with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit(fi, d) with pytest.raises(ValueError): FirstLevelModel(mask_img=None, t_r=1.0).fit(fi, d) with pytest.raises(ValueError): FirstLevelModel(mask_img=None, slice_time_ref=0.).fit(fi, d) # confounds rows do not match n_scans with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit(fi, d, conf) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del fi, func_img, mask, d, des, FUNCFILE, _
def test_high_level_glm_with_data(): with InTemporaryDirectory(): shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 16)), 3 mask, fmri_data, design_matrices = write_fake_fmri_data_and_design(shapes, rk) multi_session_model = FirstLevelModel(mask_img=None).fit( fmri_data, design_matrices=design_matrices) n_voxels = get_data(multi_session_model.masker_.mask_img_).sum() z_image = multi_session_model.compute_contrast(np.eye(rk)[1]) assert np.sum(get_data(z_image) != 0) == n_voxels assert get_data(z_image).std() < 3. # with mask multi_session_model = FirstLevelModel(mask_img=mask).fit( fmri_data, design_matrices=design_matrices) z_image = multi_session_model.compute_contrast( np.eye(rk)[:2], output_type='z_score') p_value = multi_session_model.compute_contrast( np.eye(rk)[:2], output_type='p_value') stat_image = multi_session_model.compute_contrast( np.eye(rk)[:2], output_type='stat') effect_image = multi_session_model.compute_contrast( np.eye(rk)[:2], output_type='effect_size') variance_image = multi_session_model.compute_contrast( np.eye(rk)[:2], output_type='effect_variance') assert_array_equal(get_data(z_image) == 0., get_data(load(mask)) == 0.) assert (get_data(variance_image)[get_data(load(mask)) > 0] > .001 ).all() all_images = multi_session_model.compute_contrast( np.eye(rk)[:2], output_type='all') assert_array_equal(get_data(all_images['z_score']), get_data(z_image)) assert_array_equal(get_data(all_images['p_value']), get_data(p_value)) assert_array_equal(get_data(all_images['stat']), get_data(stat_image)) assert_array_equal(get_data(all_images['effect_size']), get_data(effect_image)) assert_array_equal(get_data(all_images['effect_variance']), get_data(variance_image)) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del (all_images, design_matrices, effect_image, fmri_data, mask, multi_session_model, n_voxels, p_value, rk, shapes, stat_image, variance_image, z_image)
def test_non_parametric_inference_permutation_computation(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 1),) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) neg_log_pvals_img = non_parametric_inference(Y, design_matrix=X, mask=mask, n_perm=100) assert get_data(neg_log_pvals_img).shape == shapes[0][:3] del func_img, FUNCFILE, neg_log_pvals_img, X, Y
def test_high_level_non_parametric_inference_with_paths(): with InTemporaryDirectory(): n_perm = 100 shapes = ((7, 8, 9, 1), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] df_input = pd.DataFrame({ 'subject_label': [f'sub-{i}' for i in range(4)], 'effects_map_path': [FUNCFILE] * 4, 'map_name': [FUNCFILE] * 4 }) func_img = load(FUNCFILE) Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) c1 = np.eye(len(X.columns))[0] neg_log_pvals_imgs = [ non_parametric_inference(second_level_input, design_matrix=X, second_level_contrast=c1, first_level_contrast=FUNCFILE, mask=mask, n_perm=n_perm, verbose=1) for second_level_input in [Y, df_input] ] assert all( [isinstance(img, Nifti1Image) for img in neg_log_pvals_imgs]) for img in neg_log_pvals_imgs: assert_array_equal(img.affine, load(mask).affine) neg_log_pvals_list = [get_data(i) for i in neg_log_pvals_imgs] for neg_log_pvals in neg_log_pvals_list: assert np.all(neg_log_pvals <= -np.log10(1.0 / (n_perm + 1))) assert np.all(0 <= neg_log_pvals) masker = NiftiMasker(mask, smoothing_fwhm=2.0) with pytest.warns(UserWarning, match="Parameter smoothing_fwhm " "of the masker overridden"): non_parametric_inference(Y, design_matrix=X, second_level_contrast=c1, smoothing_fwhm=3.0, mask=masker, n_perm=n_perm) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory del X, Y, FUNCFILE, func_img, neg_log_pvals_imgs
def test_non_parametric_inference_contrast_computation(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 1), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) # asking for contrast before model fit gives error with pytest.raises(ValueError): non_parametric_inference(None, None, None, 'intercept', mask) # fit model Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) # formula should work without second-level contrast neg_log_pvals_img = non_parametric_inference(Y, design_matrix=X, mask=mask, n_perm=100) ncol = len(X.columns) c1, cnull = np.eye(ncol)[0, :], np.zeros(ncol) # formula should work with second-level contrast neg_log_pvals_img = non_parametric_inference(Y, design_matrix=X, second_level_contrast=c1, mask=mask, n_perm=100) # formula should work passing variable name directly neg_log_pvals_img = \ non_parametric_inference(Y, design_matrix=X, second_level_contrast='intercept', mask=mask, n_perm=100) # passing null contrast should give back a value error with pytest.raises(ValueError): non_parametric_inference(Y, X, cnull, 'intercept', mask) # passing wrong parameters with pytest.raises(ValueError): non_parametric_inference(Y, X, [], 'intercept', mask) # check that passing no explicit contrast when the design # matrix has more than one columns raises an error rng = np.random.RandomState(42) X = pd.DataFrame(rng.uniform(size=(4, 2)), columns=["r1", "r2"]) with pytest.raises(ValueError): non_parametric_inference(Y, X, None) del func_img, FUNCFILE, neg_log_pvals_img, X, Y
def test_slm_reporting(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 1), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) model = SecondLevelModel() Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) model = model.fit(Y, design_matrix=X) c1 = np.eye(len(model.design_matrix_.columns))[0] report_slm = glmr.make_glm_report(model, c1) # catches & raises UnicodeEncodeError in HTMLDocument.get_iframe() report_iframe = report_slm.get_iframe() # So flake8 doesn't complain about not using variable (F841) report_iframe # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del Y, FUNCFILE, func_img, model
def test_first_level_glm_computation_with_memory_caching(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 10),) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) # initialize FirstLevelModel with memory option enabled t_r = 10.0 slice_time_ref = 0. events = basic_paradigm() # Ordinary Least Squares case model = FirstLevelModel(t_r, slice_time_ref, mask_img=mask, drift_model='polynomial', drift_order=3, memory='nilearn_cache', memory_level=1, minimize_memory=False) model.fit(func_img, events) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del mask, func_img, FUNCFILE, model
def test_high_level_glm_with_paths(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 1), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) # Ordinary Least Squares case model = SecondLevelModel(mask_img=mask) # asking for contrast before model fit gives error with pytest.raises(ValueError): model.compute_contrast([]) # fit model Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) model = model.fit(Y, design_matrix=X) c1 = np.eye(len(model.design_matrix_.columns))[0] z_image = model.compute_contrast(c1, output_type='z_score') assert isinstance(z_image, Nifti1Image) assert_array_equal(z_image.affine, load(mask).affine) # Provide a masker as mask_img masker = NiftiMasker(mask) with pytest.warns(UserWarning, match="Parameter memory of the masker overridden"): SecondLevelModel(mask_img=masker, verbose=1).fit(Y, design_matrix=X) # try with target_shape target_shape = (10, 10, 10) target_affine = np.eye(4) target_affine[0, 3] = 1 model = SecondLevelModel(mask_img=mask, target_shape=target_shape, target_affine=target_affine) z_image = model.fit(Y, design_matrix=X).compute_contrast(c1) assert_array_equal(z_image.shape, target_shape) assert_array_equal(z_image.affine, target_affine) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del Y, FUNCFILE, func_img, model
def test_second_level_contrast_computation_with_memory_caching(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 1), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) # Ordinary Least Squares case model = SecondLevelModel(mask_img=mask, memory='nilearn_cache') # fit model Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) model = model.fit(Y, design_matrix=X) ncol = len(model.design_matrix_.columns) c1 = np.eye(ncol)[0, :] # test memory caching for compute_contrast model.compute_contrast(c1, output_type='z_score') # or simply pass nothing model.compute_contrast() # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del func_img, FUNCFILE, model, X, Y
def test_high_level_glm_with_paths(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 1), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) # Ordinary Least Squares case model = SecondLevelModel(mask_img=mask) # asking for contrast before model fit gives error with pytest.raises(ValueError): model.compute_contrast([]) # fit model Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) model = model.fit(Y, design_matrix=X) c1 = np.eye(len(model.design_matrix_.columns))[0] z_image = model.compute_contrast(c1, output_type='z_score') assert isinstance(z_image, Nifti1Image) assert_array_equal(z_image.affine, load(mask).affine) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del Y, FUNCFILE, func_img, model
def test_second_level_glm_computation(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 1), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) # Ordinary Least Squares case model = SecondLevelModel(mask_img=mask) Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) model = model.fit(Y, design_matrix=X) model.compute_contrast() labels1 = model.labels_ results1 = model.results_ labels2, results2 = run_glm(model.masker_.transform(Y), X.values, 'ols') assert_almost_equal(labels1, labels2, decimal=1) assert len(results1) == len(results2) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del func_img, FUNCFILE, model, X, Y
def test_infer_effect_maps(): from nilearn.glm.second_level.second_level import _infer_effect_maps # with InTemporaryDirectory(): shapes, rk = ((7, 8, 9, 1), (7, 8, 7, 16)), 3 mask, fmri_data, design_matrices = write_fake_fmri_data_and_design( shapes, rk) func_img = load(fmri_data[0]) second_level_input = pd.DataFrame({ 'map_name': ["a", "b"], 'effects_map_path': [fmri_data[0], "bar"] }) assert _infer_effect_maps(second_level_input, "a") == [fmri_data[0]] with pytest.raises(ValueError, match="File not found: 'bar'"): _infer_effect_maps(second_level_input, "b") assert _infer_effect_maps([fmri_data[0]], None) == [fmri_data[0]] contrast = np.eye(rk)[1] second_level_input = [FirstLevelModel(mask_img=mask)] * 2 for i, model in enumerate(second_level_input): model.fit(fmri_data[i], design_matrices=design_matrices[i]) assert len(_infer_effect_maps(second_level_input, contrast)) == 2 # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del mask, fmri_data, func_img, second_level_input
def test_second_level_contrast_computation(): with InTemporaryDirectory(): shapes = ((7, 8, 9, 1), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) # Ordinary Least Squares case model = SecondLevelModel(mask_img=mask) # asking for contrast before model fit gives error with pytest.raises(ValueError): model.compute_contrast('intercept') # fit model Y = [func_img] * 4 X = pd.DataFrame([[1]] * 4, columns=['intercept']) model = model.fit(Y, design_matrix=X) ncol = len(model.design_matrix_.columns) c1, cnull = np.eye(ncol)[0, :], np.zeros(ncol) # smoke test for different contrasts in fixed effects model.compute_contrast(c1) z_image = model.compute_contrast(c1, output_type='z_score') stat_image = model.compute_contrast(c1, output_type='stat') p_image = model.compute_contrast(c1, output_type='p_value') effect_image = model.compute_contrast(c1, output_type='effect_size') variance_image = \ model.compute_contrast(c1, output_type='effect_variance') # Test output_type='all', and verify images are equivalent all_images = model.compute_contrast(c1, output_type='all') assert_array_equal(get_data(all_images['z_score']), get_data(z_image)) assert_array_equal(get_data(all_images['stat']), get_data(stat_image)) assert_array_equal(get_data(all_images['p_value']), get_data(p_image)) assert_array_equal(get_data(all_images['effect_size']), get_data(effect_image)) assert_array_equal(get_data(all_images['effect_variance']), get_data(variance_image)) # formula should work (passing variable name directly) model.compute_contrast('intercept') # or simply pass nothing model.compute_contrast() # passing null contrast should give back a value error with pytest.raises(ValueError): model.compute_contrast(cnull) # passing wrong parameters with pytest.raises(ValueError): model.compute_contrast([]) with pytest.raises(ValueError): model.compute_contrast(c1, None, '') with pytest.raises(ValueError): model.compute_contrast(c1, None, []) with pytest.raises(ValueError): model.compute_contrast(c1, None, None, '') # check that passing no explicit contrast when the design # matrix has more than one columns raises an error rng = np.random.RandomState(42) X = pd.DataFrame(rng.uniform(size=(4, 2)), columns=["r1", "r2"]) model = model.fit(Y, design_matrix=X) with pytest.raises(ValueError): model.compute_contrast(None) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del func_img, FUNCFILE, model, X, Y
def test_fmri_inputs_for_non_parametric_inference(): # Test processing of FMRI inputs with InTemporaryDirectory(): # prepare fake data rng = np.random.RandomState(42) p, q = 80, 10 X = rng.standard_normal(size=(p, q)) shapes = ((7, 8, 9, 10), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) T = func_img.shape[-1] des = pd.DataFrame(np.ones((T, 1)), columns=['a']) des_fname = 'design.csv' des.to_csv(des_fname) # prepare correct input first level models flm = FirstLevelModel(subject_label='01').fit(FUNCFILE, design_matrices=des) # prepare correct input dataframe and lists shapes = ((7, 8, 9, 1), ) _, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] dfcols = ['subject_label', 'map_name', 'effects_map_path'] dfrows = [['01', 'a', FUNCFILE], ['02', 'a', FUNCFILE], ['03', 'a', FUNCFILE]] niidf = pd.DataFrame(dfrows, columns=dfcols) niimgs = [FUNCFILE, FUNCFILE, FUNCFILE] niimg_4d = concat_imgs(niimgs) confounds = pd.DataFrame([['01', 1], ['02', 2], ['03', 3]], columns=['subject_label', 'conf1']) sdes = pd.DataFrame(X[:3, :3], columns=['intercept', 'b', 'c']) # test missing second-level contrast # niimgs as input with pytest.raises(ValueError): non_parametric_inference(niimgs, None, sdes) with pytest.raises(ValueError): non_parametric_inference(niimgs, confounds, sdes) # 4d niimg as input with pytest.raises(ValueError): non_parametric_inference(niimg_4d, None, sdes) # test wrong input errors # test first level model with pytest.raises(ValueError): non_parametric_inference(flm) # test list of less than two niimgs with pytest.raises(ValueError): non_parametric_inference([FUNCFILE]) # test dataframe with pytest.raises(ValueError): non_parametric_inference(niidf) # test niimgs requirements with pytest.raises(ValueError): non_parametric_inference(niimgs) with pytest.raises(ValueError): non_parametric_inference(niimgs + [[]], confounds) with pytest.raises(ValueError): non_parametric_inference([FUNCFILE]) # test other objects with pytest.raises(ValueError): non_parametric_inference('random string object') del X, FUNCFILE, func_img
def test_fmri_inputs(): # Test processing of FMRI inputs with InTemporaryDirectory(): # prepare fake data rng = np.random.RandomState(42) p, q = 80, 10 X = rng.standard_normal(size=(p, q)) shapes = ((7, 8, 9, 10), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) T = func_img.shape[-1] des = pd.DataFrame(np.ones((T, 1)), columns=['a']) des_fname = 'design.csv' des.to_csv(des_fname) # prepare correct input first level models flm = FirstLevelModel(subject_label='01').fit(FUNCFILE, design_matrices=des) flms = [flm, flm, flm] # prepare correct input dataframe and lists shapes = ((7, 8, 9, 1), ) _, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] dfcols = ['subject_label', 'map_name', 'effects_map_path'] dfrows = [['01', 'a', FUNCFILE], ['02', 'a', FUNCFILE], ['03', 'a', FUNCFILE]] niidf = pd.DataFrame(dfrows, columns=dfcols) niimgs = [FUNCFILE, FUNCFILE, FUNCFILE] niimg_4d = concat_imgs(niimgs) confounds = pd.DataFrame([['01', 1], ['02', 2], ['03', 3]], columns=['subject_label', 'conf1']) sdes = pd.DataFrame(X[:3, :3], columns=['intercept', 'b', 'c']) # smoke tests with correct input # First level models as input SecondLevelModel(mask_img=mask).fit(flms) SecondLevelModel().fit(flms) # Note : the following one creates a singular design matrix SecondLevelModel().fit(flms, confounds) SecondLevelModel().fit(flms, None, sdes) # dataframes as input SecondLevelModel().fit(niidf) SecondLevelModel().fit(niidf, confounds) SecondLevelModel().fit(niidf, confounds, sdes) SecondLevelModel().fit(niidf, None, sdes) # niimgs as input SecondLevelModel().fit(niimgs, None, sdes) # 4d niimg as input SecondLevelModel().fit(niimg_4d, None, sdes) # test wrong input errors # test first level model requirements with pytest.raises(ValueError): SecondLevelModel().fit(flm) with pytest.raises(ValueError): SecondLevelModel().fit([flm]) # test dataframe requirements with pytest.raises(ValueError): SecondLevelModel().fit(niidf['subject_label']) # test niimgs requirements with pytest.raises(ValueError): SecondLevelModel().fit(niimgs) with pytest.raises(ValueError): SecondLevelModel().fit(niimgs + [[]], confounds) # test first_level_conditions, confounds, and design with pytest.raises(ValueError): SecondLevelModel().fit(flms, ['', []]) with pytest.raises(ValueError): SecondLevelModel().fit(flms, []) with pytest.raises(ValueError): SecondLevelModel().fit(flms, confounds['conf1']) with pytest.raises(ValueError): SecondLevelModel().fit(flms, None, [])
def test_fmri_inputs(): # Test processing of FMRI inputs with InTemporaryDirectory(): shapes = ((7, 8, 9, 10), ) mask, FUNCFILE, _ = write_fake_fmri_data_and_design(shapes) FUNCFILE = FUNCFILE[0] func_img = load(FUNCFILE) T = func_img.shape[-1] conf = pd.DataFrame([0, 0]) des = pd.DataFrame(np.ones((T, 1)), columns=['']) des_fname = 'design.csv' des.to_csv(des_fname) events = basic_paradigm() for fi in func_img, FUNCFILE: for d in des, des_fname: FirstLevelModel().fit(fi, design_matrices=d) FirstLevelModel(mask_img=None).fit([fi], design_matrices=d) FirstLevelModel(mask_img=mask).fit(fi, design_matrices=[d]) FirstLevelModel(mask_img=mask).fit([fi], design_matrices=[d]) with pytest.warns(UserWarning, match="If design matrices " "are supplied"): # test with confounds FirstLevelModel(mask_img=mask).fit([fi], design_matrices=[d], confounds=conf) # Provide t_r, confounds, and events but no design matrix FirstLevelModel(mask_img=mask, t_r=2.0).fit( fi, confounds=pd.DataFrame([0] * 10, columns=['conf']), events=events) # Same, but check that an error is raised if there is a # mismatch in the dimensions of the inputs with pytest.raises(ValueError, match="Rows in confounds does not match"): FirstLevelModel(mask_img=mask, t_r=2.0).fit(fi, confounds=conf, events=events) # test with confounds as numpy array FirstLevelModel(mask_img=mask).fit([fi], design_matrices=[d], confounds=conf.values) FirstLevelModel(mask_img=mask).fit([fi, fi], design_matrices=[d, d]) FirstLevelModel(mask_img=None).fit((fi, fi), design_matrices=(d, d)) with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit([fi, fi], d) with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit(fi, [d, d]) # At least paradigms or design have to be given with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit(fi) # If paradigms are given then both tr and slice time ref were # required with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit(fi, d) with pytest.raises(ValueError): FirstLevelModel(mask_img=None, t_r=1.0).fit(fi, d) with pytest.raises(ValueError): FirstLevelModel(mask_img=None, slice_time_ref=0.).fit(fi, d) # confounds rows do not match n_scans with pytest.raises(ValueError): FirstLevelModel(mask_img=None).fit(fi, d, conf) # Delete objects attached to files to avoid WindowsError when deleting # temporary directory (in Windows) del fi, func_img, mask, d, des, FUNCFILE, _