Exemplo n.º 1
0
def run_centernifti(
    input_dir: PathLike, output_dir: PathLike, ref_dir: PathLike
) -> None:
    from clinica.iotools.utils.data_handling import center_all_nifti

    output_dir = output_dir / "bids_centered"
    bids_dir = input_dir / "bids"

    all_modalities = [
        "t1w",
        "pet",
        "dwi",
        "magnitude",
        "bold",
        "flair",
        "t2",
        "phasediff",
    ]

    center_all_nifti(
        fspath(bids_dir),
        fspath(output_dir),
        all_modalities,
        center_all_files=True,
    )
    hashes_out = create_list_hashes(
        fspath(output_dir), extensions_to_keep=(".nii.gz", ".nii")
    )
    hashes_ref = create_list_hashes(
        fspath(ref_dir / "bids_centered"), extensions_to_keep=(".nii.gz", ".nii")
    )
    assert hashes_out == hashes_ref

    if hashes_out != hashes_ref:
        raise RuntimeError("Hashes of nii* files are different between out and ref")
Exemplo n.º 2
0
def test_run_CenterNifti(cmdopt):
    from clinica.iotools.utils.data_handling import center_all_nifti
    from os.path import dirname, join, abspath

    root = dirname(abspath(join(abspath(__file__), pardir)))
    root = join(root, 'data', 'CenterNifti')

    clean_folder(join(root, 'out', 'bids_centered'), recreate=True)

    bids_dir = join(root, 'in', 'bids')
    output_dir = join(root, 'out', 'bids_centered')

    all_modalities = [
        't1w', 'pet', 'dwi', 'magnitude', 'bold', 'flair', 't2', 'phasediff'
    ]

    center_all_nifti(bids_dir,
                     output_dir,
                     all_modalities,
                     center_all_files=True)
    hashes_out = create_list_hashes(output_dir,
                                    extensions_to_keep=('.nii.gz', '.nii'))
    hashes_ref = create_list_hashes(join(root, 'ref', 'bids_centered'),
                                    extensions_to_keep=('.nii.gz', '.nii'))

    if hashes_out != hashes_ref:
        raise RuntimeError(
            'Hashes of nii* files are different between out and ref')
    clean_folder(join(root, 'out', 'bids_centered'), recreate=False)
Exemplo n.º 3
0
def test_run_CenterNifti(cmdopt):
    from os.path import abspath, dirname, join

    from clinica.iotools.utils.data_handling import center_all_nifti

    root = dirname(abspath(join(abspath(__file__), pardir, pardir)))
    root = join(root, "data", "CenterNifti")

    clean_folder(join(root, "out", "bids_centered"), recreate=True)

    bids_dir = join(root, "in", "bids")
    output_dir = join(root, "out", "bids_centered")

    all_modalities = [
        "t1w",
        "pet",
        "dwi",
        "magnitude",
        "bold",
        "flair",
        "t2",
        "phasediff",
    ]

    center_all_nifti(bids_dir,
                     output_dir,
                     all_modalities,
                     center_all_files=True)
    hashes_out = create_list_hashes(output_dir,
                                    extensions_to_keep=(".nii.gz", ".nii"))
    hashes_ref = create_list_hashes(join(root, "ref", "bids_centered"),
                                    extensions_to_keep=(".nii.gz", ".nii"))

    if hashes_out != hashes_ref:
        raise RuntimeError(
            "Hashes of nii* files are different between out and ref")
    clean_folder(join(root, "out", "bids_centered"), recreate=False)
Exemplo n.º 4
0
def center_nifti(
    bids_directory: str,
    output_bids_directory: str,
    modalities: Optional[List[str]] = None,
    center_all_files: bool = False,
) -> None:
    """Center NIfTI files in a BIDS dataset.

    This tool is mainly useful as a preprocessing step of SPM. In some cases, SPM is not able to segment T1 volumes
    because their respective center is not aligned with the origin of the world coordinate system. By default, only
    images detected as problematic are converted from INPUT_BIDS_DIRECTORY to OUTPUT_BIDS_DIRECTORY, whilst the others
    are copied verbatim.
    """
    import sys
    import time
    from os import listdir, makedirs
    from os.path import isfile, join

    from clinica.iotools.utils.data_handling import (
        center_all_nifti,
        write_list_of_files,
    )
    from clinica.utils.stream import cprint

    # check that output_folder does not exist, or is an empty folder
    try:
        makedirs(output_bids_directory)
    except FileExistsError:
        file_list = [
            file for file in listdir(output_bids_directory)
            if not file.startswith(".")
        ]
        if file_list:
            click.echo(
                "Target BIDS directory is not empty. Existing files may be overwritten."
            )
            if not click.confirm("Do you wish to continue?"):
                click.echo("Clinica will now exit...")
                sys.exit(0)

    cprint("Clinica is now centering the requested images.")

    centered_files = center_all_nifti(
        bids_directory,
        output_bids_directory,
        modalities,
        center_all_files,
    )

    # Write list of created files
    timestamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(time.time()))
    log_file = join(output_bids_directory,
                    "centered_nifti_list_" + timestamp + ".txt")
    # If an error happen while creating the file, the function returns Nan
    if not write_list_of_files(centered_files, log_file):
        cprint("Could not create log file.")

    # Final message
    cprint(
        f"{str(len(centered_files))} NIfTI files/images of BIDS folder:\n"
        f"\t{bids_directory}\n"
        f"for the modalities {modalities} have been centered in output folder:\n"
        f"\t{output_bids_directory}")
    if isfile(log_file):
        cprint(
            f"The list of centered NIfTI files is available here: {log_file}.")
    cprint(
        "Please note that the rest of the input BIDS folder has also been copied to the output folder."
    )
Exemplo n.º 5
0
    def run_command(self, args):
        import sys
        import time
        from os import listdir, makedirs
        from os.path import abspath, isdir, isfile, join

        from colorama import Fore

        from clinica.iotools.utils.data_handling import (
            center_all_nifti,
            write_list_of_files,
        )
        from clinica.utils.stream import cprint

        # check that output_folder does not exist, or is an empty folder
        if isdir(args.output_bids_directory):
            file_list = [
                file for file in listdir(args.output_bids_directory)
                if not file.startswith(".")
            ]
            if len(file_list) > 0:
                error_str = (
                    f"{Fore.YELLOW}[Warning] Some files or directory have been found "
                    f"in {{abspath(args.output_bids_directory)}}: \n")
                for f in file_list:
                    error_str += "\t" + f + "\n"
                error_str += "Do you wish to continue ? (If yes, this may overwrite the files mentioned above)."
                error_str += Fore.RESET
                cprint(error_str)
                while True:
                    cprint("Your answer [yes/no]:")
                    answer = input()
                    if answer.lower() in ["yes", "no"]:
                        break
                    else:
                        cprint(
                            f"{Fore.RED}You must answer yes or no{Fore.RESET}")
                if answer.lower() == "no":
                    cprint(f"{Fore.RED}Clinica will now exit...{Fore.RESET}")
                    sys.exit(0)
        else:
            makedirs(args.output_bids_directory)

        split_modality = args.modality.split(" ")
        # Remove empty str in list
        split_modality = [element for element in split_modality if element]

        cprint("Clinica is now centering the requested images.")

        centered_files = center_all_nifti(
            abspath(args.bids_directory),
            abspath(args.output_bids_directory),
            split_modality,
            center_all_files=args.center_all_files,
        )

        # Write list of created files
        timestamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(time.time()))
        log_file = abspath(
            join(args.output_bids_directory,
                 "centered_nifti_list_" + timestamp + ".txt"))
        # If an error happen while creating the file, the function returns Nan
        if not write_list_of_files(centered_files, log_file):
            cprint(
                f"{Fore.YELLOW}[Warning] Could not create log file.{Fore.RESET}"
            )

        # Final message
        cprint(
            f"{Fore.GREEN}{str(len(centered_files))} NIfTI files/images of BIDS folder:\n\t "
            f"{Fore.BLUE}{abspath(args.bids_directory)}"
            f"{Fore.GREEN}\n for the modalities "
            f"{Fore.YELLOW}{args.modality}"
            f"{Fore.GREEN} have been centered in output folder:\n\t"
            f"{Fore.BLUE}{abspath(args.output_bids_directory)}{Fore.RESET}")
        if isfile(log_file):
            cprint(
                f"{Fore.GREEN}The list of centered NIfTI files is available here: {Fore.BLUE}{log_file}{Fore.RESET}"
            )
        cprint(
            "Please note that the rest of the input BIDS folder has also been copied to the output folder."
        )
Exemplo n.º 6
0
    def run_command(self, args):
        from colorama import Fore
        from os.path import isdir, abspath, join, isfile
        from os import listdir
        from os import makedirs
        from clinica.iotools.utils.data_handling import center_all_nifti, write_list_of_files
        from clinica.utils.stream import cprint
        import sys
        import time

        # check that output_folder does not exist, or is an empty folder
        if isdir(args.output_bids_directory):
            file_list = [
                file for file in listdir(args.output_bids_directory)
                if not file.startswith('.')
            ]
            if len(file_list) > 0:
                error_str = Fore.YELLOW + '[Warning] Some files or directory have been found in ' \
                            + abspath(args.output_bids_directory) + ': \n'
                for f in file_list:
                    error_str += '\t' + f + '\n'
                error_str += 'Do you wish to continue ? (If yes, this may overwrite the files mentioned above).'
                error_str += Fore.RESET
                cprint(error_str)
                while True:
                    cprint('Your answer [yes/no]:')
                    answer = input()
                    if answer.lower() in ['yes', 'no']:
                        break
                    else:
                        cprint(Fore.RED + 'You must answer yes or no' +
                               Fore.RESET)
                if answer.lower() == 'no':
                    cprint(Fore.RED + 'Clinica will now exit...' + Fore.RESET)
                    sys.exit(0)
        else:
            makedirs(args.output_bids_directory)

        split_modality = args.modality.split(' ')
        # Remove empty str in list
        split_modality = [element for element in split_modality if element]

        cprint('Clinica is now centering the requested images.')

        centered_files = center_all_nifti(
            abspath(args.bids_directory),
            abspath(args.output_bids_directory),
            split_modality,
            center_all_files=args.center_all_files)

        # Write list of created files
        timestamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(time.time()))
        log_file = abspath(
            join(args.output_bids_directory,
                 'centered_nifti_list_' + timestamp + '.txt'))
        # If an error happen while creating the file, the function returns Nan
        if not write_list_of_files(centered_files, log_file):
            cprint(Fore.YELLOW + '[Warning] Could not create log file' +
                   Fore.RESET)

        # Final message
        cprint(Fore.GREEN + str(len(centered_files)) +
               ' NIfTI files/images of BIDS folder:\n\t ' + Fore.BLUE +
               abspath(args.bids_directory) + Fore.GREEN +
               '\n for the modalities ' + Fore.YELLOW + args.modality +
               Fore.GREEN + ' have been centered in output folder:\n\t' +
               Fore.BLUE + abspath(args.output_bids_directory) + Fore.RESET)
        if isfile(log_file):
            cprint(Fore.GREEN +
                   'The list of centered NIfTI files is available here : ' +
                   Fore.BLUE + log_file + Fore.RESET)
        cprint(
            'Please note that the rest of the input BIDS folder has also been copied to the output folder.'
        )