Esempio n. 1
0
def atlas_statistics(in_image, atlas_list):
    """
    For each atlas name provided it calculates for the input image the mean for each region in the atlas and saves it to a TSV file.

    Args:
        in_image: A Nifti image
        atlas_list: List of names of atlas to be applied

    Returns:
        List of paths to TSV files
    """
    from os.path import abspath, join
    from nipype.utils.filemanip import split_filename
    from clinica.utils.atlas import AtlasAbstract
    from clinica.utils.statistics import statistics_on_atlas
    from clinica.utils.filemanip import get_subject_id
    from clinica.utils.ux import print_end_image
    subject_id = get_subject_id(in_image)

    orig_dir, base, ext = split_filename(in_image)
    atlas_classes = AtlasAbstract.__subclasses__()
    atlas_statistics_list = []
    for atlas in atlas_list:
        for atlas_class in atlas_classes:
            if atlas_class.get_name_atlas() == atlas:
                out_atlas_statistics = abspath(
                    join('./' + base + '_space-' + atlas +
                         '_map-graymatter_statistics.tsv'))
                statistics_on_atlas(in_image, atlas_class(),
                                    out_atlas_statistics)
                atlas_statistics_list.append(out_atlas_statistics)
    print_end_image(subject_id)
    return atlas_statistics_list
Esempio n. 2
0
def print_end_pipeline(t1w, final_file):
    """
    Display end message for <subject_id> when <final_file> is connected.
    """
    from clinica.utils.ux import print_end_image
    from clinica.utils.filemanip import get_subject_id
    print_end_image(get_subject_id(t1w))
def save_to_caps(source_dir, caps_dir, overwrite_caps, pipeline_parameters):
    """Save `source_dir`/ to CAPS folder.

    This function copies outputs of `source_dir`/ to
    `caps_dir`/groups/<group_id>/<statistics>/surfstat_<glm_type>/

    The `source_dir`/ folder should contain the following elements:
        - group-<group_label>_<group_1_or_2>-lt-<group_1_or_2>_measure-<measure>_fwhm-<label>_suffix.ext
    or
        - group-<group_label>_correlation-<label>_contrast-{-|+}_measure-<measure>_fwhm-<label>_suffix.ext
    and
        - group-<group_label>_covariates.tsv
        - group-<group_label>_glm.json

    Raise:
        NotImplementedError: If overwrite_caps=True.
    """
    import os
    import shutil

    from clinica.utils.ux import print_end_image

    group_id = "group-" + pipeline_parameters["group_label"]

    if pipeline_parameters["glm_type"] == "group_comparison":
        surfstat_folder = "surfstat_" + pipeline_parameters["glm_type"]
    elif pipeline_parameters["glm_type"] == "correlation":
        surfstat_folder = "surfstat_" + pipeline_parameters[
            "glm_type"] + "_analysis"
    else:
        raise NotImplementedError(
            "The other GLM situations have not been implemented in this pipeline."
        )

    destination_dir = os.path.join(os.path.expanduser(caps_dir), "groups",
                                   group_id, "statistics", surfstat_folder)

    if overwrite_caps:
        raise NotImplementedError(
            "save_to_caps(overwrite_caps=True) not implemented")
    shutil.copytree(source_dir, destination_dir, symlinks=True)
    print_end_image(group_id)
Esempio n. 4
0
def print_end_pipeline(in_bids_or_caps_file: str, final_file: str) -> None:
    from clinica.utils.filemanip import get_subject_id
    from clinica.utils.ux import print_end_image

    print_end_image(get_subject_id(in_bids_or_caps_file))
Esempio n. 5
0
def print_end_pipeline(image_id, final_file):
    """Display end message for `image_id` when `final_file` is connected."""
    from clinica.utils.ux import print_end_image

    print_end_image(image_id)
Esempio n. 6
0
def save_to_caps(source_dir, image_id, caps_dir, overwrite_caps=False):
    """Save `source_dir`/`image_id`/ to CAPS folder.

    This function copies outputs of `source_dir`/`image_id`/ to
    `caps_dir`/subjects/<participant_id>/<session_id>/t1_freesurfer_cross_sectional/
    where `image_id` = <participant_id>_<session_id>.

    The `source_dir`/`image_id`/ folder should contain the following elements:
        - fsaverage, lh.EC_average and rh.EC_average symbolic links
        - `image_id`/ folder containing the FreeSurfer segmentation
        - regional_measures/ folder containing TSV files

    Notes:
        We do not need to check the line "finished without error" in scripts/recon-all.log.
        If an error occurs, it will be detected by Nipype and the next nodes (including
        save_to_caps will not be called).

    Raise:
        FileNotFoundError: If symbolic links in `source_dir`/`image_id` folder are not removed
        IOError: If the `source_dir`/`image_id` folder does not contain FreeSurfer segmentation.
    """
    import os
    import datetime
    import errno
    import shutil
    from colorama import Fore
    from clinica.utils.stream import cprint
    from clinica.utils.ux import print_end_image

    participant_id = image_id.split('_')[0]
    session_id = image_id.split('_')[1]

    destination_dir = os.path.join(os.path.expanduser(caps_dir), 'subjects',
                                   participant_id, session_id, 't1',
                                   'freesurfer_cross_sectional')

    representative_file = os.path.join(image_id, 'mri', 'aparc+aseg.mgz')
    representative_source_file = os.path.join(os.path.expanduser(source_dir),
                                              image_id, representative_file)
    representative_destination_file = os.path.join(destination_dir,
                                                   representative_file)
    if os.path.isfile(representative_source_file):
        # Remove symbolic links before the copy
        try:
            os.unlink(
                os.path.join(os.path.expanduser(source_dir), image_id,
                             'fsaverage'))
            os.unlink(
                os.path.join(os.path.expanduser(source_dir), image_id,
                             'lh.EC_average'))
            os.unlink(
                os.path.join(os.path.expanduser(source_dir), image_id,
                             'rh.EC_average'))
        except FileNotFoundError as e:
            if e.errno != errno.ENOENT:
                raise e

        if os.path.isfile(representative_destination_file):
            if overwrite_caps:
                shutil.rmtree(destination_dir)
            shutil.copytree(os.path.join(source_dir, image_id),
                            destination_dir,
                            symlinks=True)
            print_end_image(image_id)
    else:
        now = datetime.datetime.now().strftime('%H:%M:%S')
        cprint('%s[%s] %s does not contain mri/aseg+aparc.mgz file. '
               'Copy will be skipped.%s' %
               (Fore.YELLOW, now, image_id.replace('_', ' | '), Fore.RESET))
    return image_id
Esempio n. 7
0
def print_end_pipeline(subject_id, final_file):
    """Display end message for <subject_id> when <final_file> is connected."""
    from clinica.utils.ux import print_end_image

    print_end_image(subject_id)
Esempio n. 8
0
def save_to_caps(source_dir,
                 image_id,
                 list_session_ids,
                 caps_dir,
                 overwrite_caps=False):
    """Save `source_dir`/`image_id`/ to CAPS folder.

    This function copies FreeSurfer segmentation and regional_measures folder of `source_dir`/`image_id`/ to
    `caps_dir`/subjects/<participant_id>/<long_id>/freesurfer_unbiased_template/
    where `image_id` = <participant_id>_<long_id>.

    The `source_dir`/`image_id`/ folder should contain the following elements:
        - fsaverage, lh.EC_average and rh.EC_average symbolic links automatically generated by recon-all
        - symbolic links to cross-sectional segmentation(s) and unbiased template needed for recon-all
        - <participant_id>_<long_id>/ folder containing the FreeSurfer segmentation

    Notes:
        We do not need to check the line "finished without error" in scripts/recon-all.log.
        If an error occurs, it will be detected by Nipype and the next nodes (i.e. save_to_caps will not be called).
    """
    import os
    import datetime
    import shutil
    from colorama import Fore
    from clinica.utils.stream import cprint
    from clinica.utils.longitudinal import save_long_id
    from clinica.utils.ux import print_end_image

    participant_id = image_id.split('_')[0]
    long_id = image_id.split('_')[1]

    destination_dir = os.path.join(os.path.expanduser(caps_dir), 'subjects',
                                   participant_id, long_id,
                                   'freesurfer_unbiased_template')

    # Save <long_id>_sessions.tsv to retrieve sessions used to generate <long_id>
    sessions_tsv_path = os.path.join(os.path.expanduser(caps_dir), 'subjects',
                                     participant_id, long_id)
    if not os.path.isfile(
            os.path.join(sessions_tsv_path, long_id + '_sessions.tsv')):
        save_long_id(list_session_ids, sessions_tsv_path,
                     long_id + '_sessions.tsv')

    # Save FreeSurfer segmentation
    representative_file = os.path.join(image_id, 'mri', 'aparc+aseg.mgz')
    representative_source_file = os.path.join(os.path.expanduser(source_dir),
                                              image_id, representative_file)
    representative_destination_file = os.path.join(destination_dir,
                                                   representative_file)
    if os.path.isfile(representative_source_file):
        if os.path.isfile(representative_destination_file):
            if overwrite_caps:
                shutil.rmtree(destination_dir)
                shutil.copytree(src=os.path.join(source_dir, image_id,
                                                 image_id),
                                dst=os.path.join(destination_dir, image_id),
                                symlinks=True)
        else:
            shutil.copytree(src=os.path.join(source_dir, image_id, image_id),
                            dst=os.path.join(destination_dir, image_id),
                            symlinks=True)
        print_end_image(image_id)
    else:
        now = datetime.datetime.now().strftime('%H:%M:%S')
        cprint(
            '%s[%s] %s does not contain mri/aseg+aparc.mgz file. Copy will be skipped.%s'
            % (Fore.YELLOW, now, image_id.replace('_', ' | '), Fore.RESET))
    return image_id
Esempio n. 9
0
def save_to_caps(source_dir, image_id, caps_dir, overwrite_caps=False):
    """Save `source_dir`/`image_id`/ to CAPS folder.

    This function copies FreeSurfer segmentation and regional_measures folder of `source_dir`/`image_id`/ to
    `caps_dir`/subjects/<participant_id>/<session_id>/t1_freesurfer_cross_sectional/
    where `image_id` = <participant_id>_<session_id>.

    The `source_dir`/`image_id`/ folder should contain the following elements:
        - fsaverage, lh.EC_average and rh.EC_average symbolic links automatically generated by recon-all
        - `image_id`/ folder containing the FreeSurfer segmentation
        - regional_measures/ folder containing TSV files

    Notes:
        We do not need to check the line "finished without error" in scripts/recon-all.log.
        If an error occurs, it will be detected by Nipype and the next nodes (i.e.  save_to_caps will not be called).
    """
    import os
    import shutil

    from clinica.utils.stream import cprint
    from clinica.utils.ux import print_end_image

    participant_id = image_id.split("_")[0]
    session_id = image_id.split("_")[1]

    destination_dir = os.path.join(
        os.path.expanduser(caps_dir),
        "subjects",
        participant_id,
        session_id,
        "t1",
        "freesurfer_cross_sectional",
    )

    # Save FreeSurfer segmentation
    representative_file = os.path.join(image_id, "mri", "aparc+aseg.mgz")
    representative_source_file = os.path.join(os.path.expanduser(source_dir),
                                              image_id, representative_file)
    representative_destination_file = os.path.join(destination_dir,
                                                   representative_file)
    if os.path.isfile(representative_source_file):
        if os.path.isfile(representative_destination_file):
            if overwrite_caps:
                shutil.rmtree(destination_dir)
                shutil.copytree(
                    src=os.path.join(source_dir, image_id, image_id),
                    dst=os.path.join(destination_dir, image_id),
                    symlinks=True,
                )
                shutil.copytree(
                    src=os.path.join(source_dir, image_id,
                                     "regional_measures"),
                    dst=os.path.join(destination_dir, "regional_measures"),
                    symlinks=True,
                )
        else:
            shutil.copytree(
                src=os.path.join(source_dir, image_id, image_id),
                dst=os.path.join(destination_dir, image_id),
                symlinks=True,
            )
            shutil.copytree(
                src=os.path.join(source_dir, image_id, "regional_measures"),
                dst=os.path.join(destination_dir, "regional_measures"),
                symlinks=True,
            )
        print_end_image(image_id)
    else:
        cprint(
            msg=
            f"{image_id.replace('_', ' | ')} does not contain mri/aseg+aparc.mgz file. Copy will be skipped.",
            lvl="warning",
        )
    return image_id
def save_to_caps(source_dir, subject_id, caps_dir, overwrite_caps=False):
    """Save `source_dir`/`subject_id`/ to CAPS folder.

    This function copies FreeSurfer segmentation and regional_measures folder of `source_dir`/`image_id`/ to
    `caps_dir`/subjects/<participant_id>/<session_id>/<long_id>/t1_freesurfer_longitudinal/
    where `image_id` = <participant_id>_<session_id>_<long_id>.

    The `source_dir`/`image_id`/ folder should contain the following elements:
        - fsaverage, lh.EC_average and rh.EC_average symbolic links automatically generated by recon-all
        - symbolic links to cross-sectional segmentation(s) and unbiased template needed for recon-all
        - <participant_id>_<session_id>.long.<participant_id>_<long_id>/ folder containing the FreeSurfer segmentation
        - regional_measures/ folder containing TSV files

    Notes:
        We do not need to check the line "finished without error" in scripts/recon-all.log.
        If an error occurs, it will be detected by Nipype and the next nodes (i.e. save_to_caps will not be called).
    """
    import datetime
    import os
    import shutil

    from colorama import Fore

    from clinica.utils.freesurfer import extract_image_id_from_longitudinal_segmentation
    from clinica.utils.stream import cprint
    from clinica.utils.ux import print_end_image

    image_id = extract_image_id_from_longitudinal_segmentation(subject_id)
    participant_id = image_id.participant_id
    session_id = image_id.session_id
    long_id = image_id.long_id
    str_image_id = (image_id.participant_id + "_" + image_id.session_id + "_" +
                    image_id.long_id)

    destination_dir = os.path.join(
        os.path.expanduser(caps_dir),
        "subjects",
        participant_id,
        session_id,
        "t1",
        long_id,
        "freesurfer_longitudinal",
    )

    # Save FreeSurfer segmentation
    representative_file = os.path.join(subject_id, "mri", "aparc+aseg.mgz")
    representative_source_file = os.path.join(os.path.expanduser(source_dir),
                                              str_image_id,
                                              representative_file)
    representative_destination_file = os.path.join(destination_dir,
                                                   representative_file)
    if os.path.isfile(representative_source_file):
        if os.path.isfile(representative_destination_file):
            if overwrite_caps:
                shutil.rmtree(destination_dir)
                shutil.copytree(
                    src=os.path.join(source_dir, subject_id, subject_id),
                    dst=os.path.join(destination_dir, subject_id),
                    symlinks=True,
                )
                shutil.copytree(
                    src=os.path.join(source_dir, subject_id,
                                     "regional_measures"),
                    dst=os.path.join(destination_dir, "regional_measures"),
                    symlinks=True,
                )
        else:
            shutil.copytree(
                src=os.path.join(source_dir, str_image_id, subject_id),
                dst=os.path.join(destination_dir, subject_id),
                symlinks=True,
            )
            shutil.copytree(
                src=os.path.join(source_dir, str_image_id,
                                 "regional_measures"),
                dst=os.path.join(destination_dir, "regional_measures"),
                symlinks=True,
            )
        print_end_image(str_image_id)
    else:
        now = datetime.datetime.now().strftime("%H:%M:%S")
        cprint(
            f"{Fore.YELLOW}[{now}] {subject_id.replace('_', ' | ')}  does not contain "
            f"mri/aseg+aparc.mgz file. Copy will be skipped.{Fore.RESET}")

    return str_image_id