Beispiel #1
0
def test_pscalar():
    scalar_map = create_scalar_map((0, ))
    parcel_map = create_parcel_map((1, ))
    matrix = ci.Cifti2Matrix()
    matrix.append(scalar_map)
    matrix.append(parcel_map)
    hdr = ci.Cifti2Header(matrix)
    data = np.random.randn(2, 3)
    img = ci.Cifti2Image(data, hdr)
    img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_PARCELLATED_SCALAR')

    with InTemporaryDirectory():
        ci.save(img, 'test.pscalar.nii')
        img2 = nib.load('test.pscalar.nii')
        assert_equal(img2.nifti_header.get_intent()[0], 'ConnParcelScalr')
        assert_true(isinstance(img2, ci.Cifti2Image))
        assert_true((img2.get_data() == data).all())
        check_scalar_map(img2.header.matrix.get_index_map(0))
        check_parcel_map(img2.header.matrix.get_index_map(1))
        del img2
Beispiel #2
0
def test_dlabel():
    label_map = create_label_map((0, ))
    geometry_map = create_geometry_map((1, ))
    matrix = ci.Cifti2Matrix()
    matrix.append(label_map)
    matrix.append(geometry_map)
    hdr = ci.Cifti2Header(matrix)
    data = np.random.randn(2, 9)
    img = ci.Cifti2Image(data, hdr)
    img.nifti_header.set_intent('NIFTI_INTENT_CONNECTIVITY_DENSE_LABELS')

    with InTemporaryDirectory():
        ci.save(img, 'test.dlabel.nii')
        img2 = nib.load('test.dlabel.nii')
        assert_equal(img2.nifti_header.get_intent()[0], 'ConnDenseLabel')
        assert_true(isinstance(img2, ci.Cifti2Image))
        assert_true((img2.get_data() == data).all())
        check_label_map(img2.header.matrix.get_index_map(0))
        check_geometry_map(img2.header.matrix.get_index_map(1))
        del img2
Beispiel #3
0
def test_dpy():
    fname = 'test.bin'
    with InTemporaryDirectory():
        dpw = Dpy(fname, 'w')
        A=np.ones((5,3))
        B=2*A.copy()
        C=3*A.copy()
        dpw.write_track(A)
        dpw.write_track(B)
        dpw.write_track(C)
        dpw.write_tracks([C,B,A])
        dpw.close()
        dpr = Dpy(fname, 'r')
        assert_equal(dpr.version()=='0.0.1',True)
        T=dpr.read_tracksi([0,1,2,0,0,2])
        T2=dpr.read_tracks()
        assert_equal(len(T2),6)
        dpr.close()
        assert_array_equal(A,T[0])
        assert_array_equal(C,T[5])
Beispiel #4
0
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_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)
Beispiel #6
0
def test_create_second_level_design():
    with InTemporaryDirectory():
        shapes = ((7, 8, 9, 1),)
        mask, FUNCFILE, _ = write_fake_fmri_data(shapes)
        FUNCFILE = FUNCFILE[0]
        first_level_input = _first_level_dataframe()
        first_level_input['effects_map_path'] = [FUNCFILE] * 4
        confounds = [['01', 0.1], ['02', 0.75]]
        confounds = pd.DataFrame(confounds, columns=['subject_id', 'f1'])
        design = create_second_level_design(first_level_input, confounds)
        expected_design = np.array([[1, 0, 1, 0, 0.1], [0, 1, 1, 0, 0.1],
                                    [1, 0, 0, 1, 0.75], [0, 1, 0, 1, 0.75]])
        assert_array_equal(design, expected_design)
        assert_true(len(design.columns) == 2 + 2 + 1)
        assert_true(len(design) == 2 + 2)
        model = SecondLevelModel(mask=mask).fit(first_level_input,
                                                confounds=confounds)
        design = model.design_matrix_
        assert_array_equal(design, expected_design)
        assert_true(len(design.columns) == 2 + 2 + 1)
        assert_true(len(design) == 2 + 2)
Beispiel #7
0
def test_parcel_based_analysis():
    # Generate an image
    shape = (7, 8, 4)
    n_subj = 5
    n_parcel, nn, mu = 10, 6, 1.

    with InTemporaryDirectory() as dir_context:
        data_image = ['image_%d.nii' % i for i in range(5)]
        for datim in data_image:
            surrogate_3d_dataset(shape=shape, out_image_file=datim)
        ldata = np.random.randn(n_subj, np.prod(shape), 1)
        domain = grid_domain_from_shape(shape)
        parcels = hparcel(domain, ldata, n_parcel, mu=3.0)
        prfx = parcellation_based_analysis(parcels,
                                           data_image,
                                           test_id='one_sample',
                                           rfx_path='prfx.nii',
                                           condition_id='',
                                           swd=dir_context)
        assert exists('prfx.nii')
        assert np.abs(prfx).max() < 15
def test_pconnscalar():
    parcel_map = create_parcel_map((0, 1))
    scalar_map = create_scalar_map((2, ))

    matrix = ci.Cifti2Matrix()
    matrix.append(parcel_map)
    matrix.append(scalar_map)
    hdr = ci.Cifti2Header(matrix)
    data = np.random.randn(3, 3, 13)
    img = ci.Cifti2Image(data, hdr)

    with InTemporaryDirectory():
        ci.save(img, 'test.pconnscalar.nii')
        img2 = ci.load('test.pconnscalar.nii')
        assert_true((img2.get_data() == data).all())
        assert_equal(img2.header.matrix.get_index_map(0),
                     img2.header.matrix.get_index_map(1))

        check_parcel_map(img2.header.matrix.get_index_map(0))
        check_scalar_map(img2.header.matrix.get_index_map(2))
        del img2
Beispiel #9
0
def test_high_level_glm_with_paths():
    with InTemporaryDirectory():
        shapes = ((7, 8, 9, 1), )
        mask, FUNCFILE, _ = _write_fake_fmri_data(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
        assert_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_true(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
Beispiel #10
0
def test_io_save_peaks_error():
    with InTemporaryDirectory():
        fname = 'test.pam5'

        pam = PeaksAndMetrics()

        npt.assert_raises(IOError, save_peaks, 'test.pam', pam)
        npt.assert_raises(ValueError, save_peaks, fname, pam)

        pam.affine = np.eye(4)
        pam.peak_dirs = np.random.rand(10, 10, 10, 5, 3)
        pam.peak_values = np.zeros((10, 10, 10, 5))
        pam.peak_indices = np.zeros((10, 10, 10, 5))
        pam.shm_coeff = np.zeros((10, 10, 10, 45))
        pam.sphere = default_sphere
        pam.B = np.zeros((45, default_sphere.vertices.shape[0]))
        pam.total_weight = 0.5
        pam.ang_thr = 60
        pam.gfa = np.zeros((10, 10, 10))
        pam.qa = np.zeros((10, 10, 10, 5))
        pam.odf = np.zeros((10, 10, 10, default_sphere.vertices.shape[0]))
Beispiel #11
0
def test_trackvis():
    with InTemporaryDirectory():
        fname = 'trackvis_test.trk'
        affine = np.eye(4)

        # Test save
        trackvis_save_trk(fname, streamlines, affine, np.array([50, 50, 50]))
        tfile = nib.streamlines.load(fname)
        npt.assert_array_equal(affine, tfile.affine)
        npt.assert_array_equal(np.array([1., 1., 1.]),
                               tfile.header.get('voxel_sizes'))
        npt.assert_array_equal(np.array([50, 50, 50]),
                               tfile.header.get('dimensions'))
        npt.assert_equal(len(tfile.streamlines), len(streamlines))
        npt.assert_array_almost_equal(tfile.streamlines[1],
                                      streamline,
                                      decimal=4)

        # Test Deprecations
        npt.assert_warns(DeprecationWarning, trackvis_save_trk, fname,
                         streamlines, affine, np.array([50, 50, 50]))
Beispiel #12
0
def test_second_level_model_contrast_computation_with_memory_caching():
    with InTemporaryDirectory():
        shapes = ((7, 8, 9, 1), )
        mask, FUNCFILE, _ = _write_fake_fmri_data(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
Beispiel #13
0
def test_csv_io():
    # test the csv io on design matrices
    tr = 1.0
    frame_times = np.linspace(0, 127 * tr, 128)
    events = modulated_event_paradigm()
    DM = make_first_level_design_matrix(
        frame_times,
        events,
        hrf_model='glover',
        drift_model='polynomial',
        drift_order=3,
    )
    path = 'design_matrix.csv'
    with InTemporaryDirectory():
        DM.to_csv(path)
        DM2 = pd.read_csv(path, index_col=0)

    _, matrix, names = check_design_matrix(DM)
    _, matrix_, names_ = check_design_matrix(DM2)
    assert_almost_equal(matrix, matrix_)
    assert names == names_
def test_fmri_inputs():
    # Test processing of FMRI inputs
    with InTemporaryDirectory():
        shapes = ((7, 8, 9, 10), )
        mask, FUNCFILE, _ = write_fake_fmri_data(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=None).fit([fi], design_matrices=d)
                FirstLevelModel(mask=mask).fit(fi, design_matrices=[d])
                FirstLevelModel(mask=mask).fit([fi], design_matrices=[d])
                FirstLevelModel(mask=mask).fit([fi, fi],
                                               design_matrices=[d, d])
                FirstLevelModel(mask=None).fit((fi, fi),
                                               design_matrices=(d, d))
                assert_raises(ValueError,
                              FirstLevelModel(mask=None).fit, [fi, fi], d)
                assert_raises(ValueError,
                              FirstLevelModel(mask=None).fit, fi, [d, d])
                # At least paradigms or design have to be given
                assert_raises(ValueError, FirstLevelModel(mask=None).fit, fi)
                # If paradigms are given then both tr and slice time ref were
                # required
                assert_raises(ValueError,
                              FirstLevelModel(mask=None).fit, fi, d)
                assert_raises(ValueError,
                              FirstLevelModel(mask=None, t_r=1.0).fit, fi, d)
                assert_raises(
                    ValueError,
                    FirstLevelModel(mask=None, slice_time_ref=0.).fit, fi, d)
            # confounds rows do not match n_scans
            assert_raises(ValueError,
                          FirstLevelModel(mask=None).fit, fi, d, conf)
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
        X = pd.DataFrame(np.random.rand(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
Beispiel #16
0
def test_high_level_glm_with_data():
    # New API
    with InTemporaryDirectory():
        shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 16)), 3
        mask, fmri_data, design_matrices = write_fake_fmri_data(shapes, rk)
        multi_session_model = FirstLevelModel(mask=None).fit(
            fmri_data, design_matrices=design_matrices)
        n_voxels = multi_session_model.masker_.mask_img_.get_data().sum()
        z_image = multi_session_model.compute_contrast(np.eye(rk)[1])
        assert_equal(np.sum(z_image.get_data() != 0), n_voxels)
        assert_true(z_image.get_data().std() < 3.)

        # with mask
        multi_session_model = FirstLevelModel(mask=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(z_image.get_data() == 0.,
                           load(mask).get_data() == 0.)
        assert_true((variance_image.get_data()[load(mask).get_data() > 0] >
                     .001).all())

    all_images = multi_session_model.compute_contrast(np.eye(rk)[:2],
                                                      output_type='all')

    assert_array_equal(all_images['z_score'].get_data(), z_image.get_data())
    assert_array_equal(all_images['p_value'].get_data(), p_value.get_data())
    assert_array_equal(all_images['stat'].get_data(), stat_image.get_data())
    assert_array_equal(all_images['effect_size'].get_data(),
                       effect_image.get_data())
    assert_array_equal(all_images['effect_variance'].get_data(),
                       variance_image.get_data())
Beispiel #17
0
    def record_events(self):
        """ Records events during the interaction.

        The recording is represented as a list of VTK events that happened
        during the interaction. The recorded events are then returned.

        Returns
        -------
        events : str
            Recorded events (one per line).

        Notes
        -----
        Since VTK only allows recording events to a file, we use a
        temporary file from which we then read the events.
        """
        with InTemporaryDirectory():
            filename = "recorded_events.log"
            recorder = vtk.vtkInteractorEventRecorder()
            recorder.SetInteractor(self.iren)
            recorder.SetFileName(filename)

            def _stop_recording_and_close(obj, evt):
                recorder.Stop()
                self.iren.TerminateApp()

            self.iren.AddObserver("ExitEvent", _stop_recording_and_close)

            recorder.EnabledOn()
            recorder.Record()

            self.initialize()
            self.render()
            self.iren.Start()

            # Retrieved recorded events.
            events = open(filename).read()

        return events
def test_first_level_model_glm_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)
        model = model.fit(func_img, events)

        # Delete objects attached to files to avoid WindowsError when deleting
        # temporary directory (in Windows)
        del mask, FUNCFILE, func_img, model
Beispiel #19
0
def test_img_data_dtype():
    # Ignoring complex, binary, 128+ bit, RGBA
    nifti1_dtypes = (np.uint8, np.uint16, np.uint32, np.uint64, np.int8,
                     np.int16, np.int32, np.int64, np.float32, np.float64)
    dtype_matches = []
    with InTemporaryDirectory():
        for logical_dtype in nifti1_dtypes:
            dataobj = np.random.uniform(0, 255,
                                        size=(2, 2, 2)).astype(logical_dtype)
            for on_disk_dtype in nifti1_dtypes:
                img = Nifti1Image(dataobj, np.eye(4))
                img.set_data_dtype(on_disk_dtype)
                img.to_filename('test.nii')
                loaded = nb.load('test.nii')
                # To verify later that sometimes these differ meaningfully
                dtype_matches.append(
                    loaded.get_data_dtype() == niimg.img_data_dtype(loaded))
                assert (np.array(
                    loaded.dataobj).dtype == niimg.img_data_dtype(loaded))
    # Verify that the distinction is worth making
    assert any(dtype_matches)
    assert not all(dtype_matches)
def test_nibabel_readwritedata():
    with InTemporaryDirectory():
        for name in datafiles:
            img = nib.load(name)
            nib.save(img, 'test.nii')
            img2 = nib.load('test.nii')
            assert len(img.header.matrix) == len(img2.header.matrix)
            # Order should be preserved in load/save
            for mim1, mim2 in zip(img.header.matrix,
                                  img2.header.matrix):
                named_maps1 = [m_ for m_ in mim1
                               if isinstance(m_, ci.Cifti2NamedMap)]
                named_maps2 = [m_ for m_ in mim2
                               if isinstance(m_, ci.Cifti2NamedMap)]
                assert len(named_maps1) == len(named_maps2)
                for map1, map2 in zip(named_maps1, named_maps2):
                    assert map1.map_name == map2.map_name
                    if map1.label_table is None:
                        assert map2.label_table is None
                    else:
                        assert len(map1.label_table) == len(map2.label_table)
            assert_array_almost_equal(img.dataobj, img2.dataobj)
Beispiel #21
0
def test_slm_reporting(use_method):
    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]
        if use_method:
            report_slm = glmr.make_glm_report(model, c1)
        else:
            report_slm = model.generate_report(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_model_glm_computation():
    with InTemporaryDirectory():
        shapes = ((7, 8, 9, 10), )
        mask, FUNCFILE, _ = write_fake_fmri_data(shapes)
        FUNCFILE = FUNCFILE[0]
        func_img = load(FUNCFILE)
        # basic test based on basic_paradigm and glover hrf
        t_r = 1.0
        slice_time_ref = 0.
        paradigm = basic_paradigm()
        # ols case
        model = FirstLevelModel(t_r,
                                slice_time_ref,
                                mask=mask,
                                drift_model='polynomial',
                                drift_order=3,
                                minimize_memory=False)
        model = model.fit(func_img, paradigm)
        labels1 = model.labels_[0]
        results1 = model.results_[0]
        labels2, results2 = run_glm(model.masker_.transform(func_img),
                                    model.design_matrices_[0], 'ar1')
Beispiel #23
0
def test_second_level_model_contrast_computation():
    with InTemporaryDirectory():
        shapes = ((7, 8, 9, 1), )
        mask, FUNCFILE, _ = write_fake_fmri_data(shapes)
        FUNCFILE = FUNCFILE[0]
        func_img = load(FUNCFILE)
        # Ordinary Least Squares case
        model = SecondLevelModel(mask=mask)
        # asking for contrast before model fit gives error
        assert_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)
        model.compute_contrast(c1, output_type='z_score')
        model.compute_contrast(c1, output_type='stat')
        model.compute_contrast(c1, output_type='p_value')
        model.compute_contrast(c1, output_type='effect_size')
        model.compute_contrast(c1, output_type='effect_variance')
        # 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
        assert_raises(ValueError, model.compute_contrast, cnull)
        # passing wrong parameters
        assert_raises(ValueError, model.compute_contrast, [])
        assert_raises(ValueError, model.compute_contrast, c1, None, '')
        assert_raises(ValueError, model.compute_contrast, c1, None, [])
        assert_raises(ValueError, model.compute_contrast, c1, None, None, '')
        # check that passing no explicit contrast when the dsign
        # matrix has morr than one columns raises an error
        X = pd.DataFrame(np.random.rand(4, 2), columns=['r1', 'r2'])
        model = model.fit(Y, design_matrix=X)
        assert_raises(ValueError, model.compute_contrast, None)
Beispiel #24
0
def test_save2b():
    # A test to ensure that when a file is saved, the affine and the
    # data agree. This image comes from a NIFTI file.  This example has a
    # non-diagonal affine matrix for the spatial part, but is 'diagonal' for the
    # space part.
    #
    # make a 5x5 transformation (for 4d image)
    step = np.array([3.45, 2.3, 4.5, 6.9])
    A = np.random.standard_normal((3, 3))
    B = np.diag(list(step) + [1])
    B[:3, :3] = A
    shape = (13, 5, 7, 3)
    cmap = api.vox2mni(B)
    data = np.random.standard_normal(shape)
    img = api.Image(data, cmap)
    with InTemporaryDirectory():
        save_image(img, TMP_FNAME)
        img2 = load_image(TMP_FNAME)
        assert_array_almost_equal(img.affine, img2.affine)
        assert_equal(img.shape, img2.shape)
        assert_array_almost_equal(img2.get_data(), img.get_data())
        del img2
Beispiel #25
0
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
Beispiel #26
0
def test_write_screen_res():
    img = ni.load_image(funcfile)
    with InTemporaryDirectory():
        res = screen(img)
        os.mkdir('myresults')
        write_screen_res(res, 'myresults', 'myana')
        pca_img = ni.load_image(pjoin('myresults', 'pca_myana.nii'))
        assert_equal(pca_img.shape, img.shape[:-1] + (10,))
        # Make sure we get the same output image even from rolled image
        # Do fancy roll to put time axis first, and slice axis last. This does
        # a stress test on the axis ordering, but also makes sure that we are
        # getting the number of components from the right place.  If we were
        # getting the number of components from the length of the last axis,
        # instead of the length of the 't' axis in the returned pca image, this
        # would be wrong (=21) which would also be more than the number of
        # basis vectors (19) so raise an error
        rimg = img.reordered_axes([3, 2, 0, 1])
        os.mkdir('rmyresults')
        rres = screen(rimg)
        write_screen_res(rres, 'rmyresults', 'myana')
        rpca_img = ni.load_image(pjoin('rmyresults', 'pca_myana.nii'))
        assert_equal(rpca_img.shape, img.shape[:-1] + (10,))
        del pca_img, rpca_img
Beispiel #27
0
def test_second_level_model_glm_computation():
    with InTemporaryDirectory():
        shapes = ((7, 8, 9, 1), )
        mask, FUNCFILE, _ = _write_fake_fmri_data(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_equal(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
Beispiel #28
0
def test_first_level_glm_computation_with_memory_caching():
    with InTemporaryDirectory():
        shapes = ((7, 8, 9, 10), )
        mask, FUNCFILE, _ = _write_fake_fmri_data(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_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
Beispiel #30
0
def test_qb_commandline_output_path_handling():
    with InTemporaryDirectory():
        # Create temporary subdirectory for input and for output
        os.mkdir('work')
        os.mkdir('output')

        os.chdir('work')
        tracks_file = get_data('fornix')

        # Need to specify an output directory with a "../" style path
        # to trigger old bug.
        cmd = [
            "dipy_quickbundles", tracks_file, '--pkl_file', 'mypickle.pkl',
            '--out_file',
            os.path.join('..', 'output', 'tracks300.trk')
        ]
        out = run_command(cmd)
        assert_equal(out[0], 0)

        # Make sure the files were created in the output directory
        os.chdir('../')
        output_files_list = glob.glob('output/tracks300_*.trk')
        assert_true(output_files_list)