"""construct experimental paradigm"""
stats_start_time = time.ctime()
tr = 7.
n_scans = 96
_duration = 6
epoch_duration = _duration * tr
conditions = ['rest', 'active'] * 8
duration = epoch_duration * np.ones(len(conditions))
onset = np.linspace(0, (len(conditions) - 1) * epoch_duration,
                    len(conditions))
paradigm = BlockParadigm(con_id=conditions, onset=onset, duration=duration)
hfcut = 2 * 2 * epoch_duration

"""fetch spm auditory data"""
_subject_data = fetch_spm_auditory_data(DATA_DIR)
subject_data = nipype_preproc_spm_utils.SubjectData()
subject_data.subject_id = "sub001"
subject_data.func = _subject_data["func"]
subject_data.anat = _subject_data["anat"]
subject_data.output_dir = os.path.join(
    OUTPUT_DIR, subject_data.subject_id)

print subject_data.func
"""preprocess the data"""
results = nipype_preproc_spm_utils.do_subjects_preproc(
    [subject_data],
    output_dir=OUTPUT_DIR,
    dataset_id="SPM single-subject auditory",
    dataset_description=DATASET_DESCRIPTION,
    do_shutdown_reloaders=False,
Example #2
0
def demo_BOLD(dataset='spm-auditory',
              QA=True,
              data_dir='/tmp/stc_demo',
              output_dir='/tmp',
              compare_with=None,
              ):
    """XXX This only works on my machine since you surely don't have
    SPM single-subject auditory data or FSL FEEDS data installed on yours ;)

    XXX TODO: interpolation can produce signal out-side the brain;
    solve this with proper masking

    Raises
    ------
    Exception

    """

    # sanitize dataset name
    assert isinstance(dataset, basestring)
    dataset = dataset.lower()

    # sanitize output dir
    if output_dir is None:
        output_dir = '/tmp'

    # demo specific imports
    import nibabel as ni
    import os
    import sys

    # load the data
    slice_order = 'ascending'
    interleaved = False
    if dataset == 'spm-auditory':
        # pypreproces path
        PYPREPROCESS_DIR = os.path.dirname(os.path.split(
                os.path.abspath(__file__))[0])
        sys.path.append(PYPREPROCESS_DIR)
        from datasets_extras import fetch_spm_auditory_data

        _subject_data = fetch_spm_auditory_data(data_dir)

        fmri_img = ni.concat_images(_subject_data['func'],)
        fmri_data = fmri_img.get_data()[:, :, :, 0, :]

        compare_with = ni.concat_images(
            [os.path.join(os.path.dirname(x),
                          "a" + os.path.basename(x))
             for x in _subject_data['func']]).get_data()

        TR = 7.
    elif dataset == 'fsl-feeds':
        PYPREPROCESS_DIR = os.path.dirname(os.path.split(
                os.path.abspath(__file__))[0])

        sys.path.append(PYPREPROCESS_DIR)
        from datasets_extras import fetch_fsl_feeds_data

        _subject_data = fetch_fsl_feeds_data(data_dir)
        if not _subject_data['func'].endswith('.gz'):
            _subject_data['func'] += '.gz'

        fmri_img = ni.load(_subject_data['func'],)
        fmri_data = fmri_img.get_data()

        TR = 3.
    elif dataset == 'localizer':
        output_filename = "/tmp/st_corrected_localizer.nii.gz"
        fmri_img = ni.load(
            "/home/elvis/.nipy/tests/data/s12069_swaloc1_corr.nii.gz")
        fmri_data = fmri_img.get_data()

        TR = 2.4
    elif dataset == 'face-rep-spm5':
        # XXX nibabel says the affines of the 3Ds are different
        fmri_img = ni.load(
            "/home/elvis/CODE/datasets/face_rep_SPM5/RawEPI/4D.nii.gz")
        fmri_data = fmri_img.get_data()

        TR = 2.
        slice_order = 'descending'
    else:
        raise Exception("Unknown dataset: %s" % dataset)

    output_filename = os.path.join(
        output_dir,
        "st_corrected_" + dataset.rstrip(" ").replace("-", "_") + ".nii.gz",
        )

    print "\r\n\t\t ---demo_BOLD (%s)---" % dataset

    # fit STC
    stc = STC()
    stc.fit(raw_data=fmri_data, slice_order=slice_order,
            interleaved=interleaved,
            )

    # do full-brain ST correction
    print "Applying full-brain STC transform..."
    corrected_fmri_data = stc.transform()
    print "Done."

    # save output unto disk
    print "Saving ST corrected image to %s..." % output_filename
    ni.save(ni.Nifti1Image(corrected_fmri_data, fmri_img.get_affine()),
            output_filename)
    print "Done."

    # QA clinic
    if QA:
        x = 32
        y = 32
        print "Starting QA clinic (free entrance to the masses)..."
        STC_QA(fmri_data, corrected_fmri_data, TR, x, y,
               compare_with=compare_with)
Example #3
0
def demo_real_BOLD(dataset='localizer',
              data_dir='/tmp/stc_demo',
              output_dir='/tmp',
              compare_with=None,
              QA=True,
              ):
    """Demo for real data.

    Parameters
    ----------
    dataset: string (optiona, defaul 'localizer')
        name of dataset to demo. Possible values are:
        spm-auditory: SPM single-subject auditory data (if absent,
                      will try to grab it over the net)
        fsl-feeds: FSL-Feeds fMRI data (if absent, will try to grab
                   it over the net)
        localizer: data used with nipy's localize_glm_ar.py demo; you'll
                   need nipy test data installed
        face-rep-SPM5 (you need to download the data and point data_dir
        to the containing folder)
    data_dir: string (optional, '/tmp/stc_demo')
        path to directory containing data; or destination
        for downloaded data (in case we fetch from the net)
    output_dir: string (optional, default "/tmp")
        path to directory where all output (niftis, etc.)
        will be written
    compare_with: 4D array (optional, default None)
        data to compare STC results with, must be same shape as
        corrected data
    QA: boolean (optional, default True)
        if set, then QA plots will be generated after STC

    Raises
    ------
    Exception

    """

    # sanitize dataset name
    assert isinstance(dataset, basestring)
    dataset = dataset.lower()

    # sanitize output dir
    if output_dir is None:
        output_dir = '/tmp'

    print "\r\n\t\t ---demo_real_BOLD (%s)---" % dataset

    # load the data
    slice_order = 'ascending'
    interleaved = False
    ref_slice = 0
    print("Loading data...")
    if dataset == 'spm-auditory':
        # pypreproces path
        PYPREPROCESS_DIR = os.path.dirname(os.path.split(
                os.path.abspath(__file__))[0])
        sys.path.append(PYPREPROCESS_DIR)
        from datasets_extras import fetch_spm_auditory_data

        _subject_data = fetch_spm_auditory_data(data_dir)

        fmri_img = ni.concat_images(_subject_data['func'],)
        fmri_data = fmri_img.get_data()[:, :, :, 0, :]

        TR = 7.
    elif dataset == 'fsl-feeds':
        PYPREPROCESS_DIR = os.path.dirname(os.path.split(
                os.path.abspath(__file__))[0])

        sys.path.append(PYPREPROCESS_DIR)
        from datasets_extras import fetch_fsl_feeds_data

        _subject_data = fetch_fsl_feeds_data(data_dir)
        if not _subject_data['func'].endswith('.gz'):
            _subject_data['func'] += '.gz'

        fmri_img = ni.load(_subject_data['func'],)
        fmri_data = fmri_img.get_data()

        TR = 3.
    elif dataset == 'localizer':
        data_path = os.path.join(
            os.environ["HOME"],
            ".nipy/tests/data/s12069_swaloc1_corr.nii.gz")
        if not os.path.exists(data_path):
            raise RuntimeError("You don't have nipy test data installed!")

        fmri_img = ni.load(data_path)
        fmri_data = fmri_img.get_data()

        TR = 2.4
    elif dataset == 'face-rep-spm5':
        # XXX nibabel says the affines of the 3Ds are different
        fmri_data = np.array([ni.load(x).get_data() for x in sorted(glob.glob(
                        os.path.join(
                            data_dir,
                            "RawEPI/sM03953_0005_*.img")))])[:, :, :, 0, :]
        if len(fmri_data) == 0:
            raise RuntimeError(
                "face-rep-SPM5 data not found in %s; install it it set the "
                "parameter data_dir to the directory containing it")

        TR = 2.
        slice_order = 'descending'
        ref_slice = fmri_data.shape[2] / 2  # middle slice
    else:
        raise RuntimeError("Unknown dataset: %s" % dataset)

    output_filename = os.path.join(
        output_dir,
        "st_corrected_" + dataset.rstrip(" ").replace("-", "_") + ".nii",
        )

    print("Done.")

    # fit STC
    stc = STC()
    stc.fit(raw_data=fmri_data,
            slice_order=slice_order,
            interleaved=interleaved,
            ref_slice=ref_slice,
            )

    # do full-brain ST correction
    stc.transform(fmri_data)
    corrected_fmri_data = stc.get_last_output_data()

    # save output unto disk
    print "Saving ST corrected image to %s..." % output_filename
    ni.save(ni.Nifti1Image(corrected_fmri_data, fmri_img.get_affine()),
            output_filename)
    print "Done."

    # QA clinic
    if QA:
        plot_slicetiming_results(fmri_data,
                                 corrected_fmri_data,
                                 TR=TR,
                                 compare_with=compare_with,
                                 suptitle_prefix=dataset,
                                 )