import yaml from typing import List from collections import deque from pathlib import Path import numpy as np import SimpleITK as sitk def print_p(text, end="\n"): """ Print function for on Peregrine. It needs a flush before printing. """ print(text, flush=True, end=end) def list_from_file(path: str) -> List: """ Returns a list of all items on each line of the text file referenced in the given path Parameters: `path (str)`: path to the text file """ print_p(path) return [line.strip() for line in open(path, "r")] def dump_dict_to_yaml( data: dict, target_dir: str, filename: str = "settings", verbose: bool = True) -> None: """ Writes the given dictionary as a yaml to the target directory. Parameters: `data (dict)`: dictionary of data. `target_dir (str)`: directory where the yaml will be saved. `` filename (str)`: name of the file without extension """ if verbose: print("\nParameters") for pair in data.items(): print(f"\t{pair}") print() path = f"{target_dir}/{filename}.yml" print_p(f"Wrote yaml to: {path}") with open(path, 'w') as outfile: yaml.dump(data, outfile, default_flow_style=False) def read_yaml_to_dict(path: str) -> dict: with open(path, 'r') as stream: try: parsed_yaml=yaml.safe_load(stream) # print(parsed_yaml) return parsed_yaml except yaml.YAMLError as exc: print(exc) def create_dirs_if_not_exists(dirs: List[str]) -> None: """ Creates the list of supplied directories if they don't exist yet. Parameters: `dirs (List[str]) or str`: list of strings representing the directories that need to be created """ if isinstance(dirs, str): dirs = [dirs] for folder in dirs: Path(folder).mkdir(parents=True, exist_ok=True) print_p(f"Created directory {folder} or it already existed.") def save_np_to_nifti(data_np: np.ndarray, target_dir: str, fname: str, target_space: List[float] = [0.5, 0.5, 3.0]): img_s = sitk.GetImageFromArray(data_np.T) img_s.SetSpacing(target_space) path = f"{target_dir}/{fname}.nii.gz" sitk.WriteImage(img_s, path) print_p(f"Saved numpy array to nifti: {path}")