|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import os |
| 3 | +import glob |
| 4 | +import json |
| 5 | +import nibabel as nib |
| 6 | +import shutil |
| 7 | +import numpy as np |
| 8 | +from tqdm import tqdm |
| 9 | +from src.wrappers.OsipiBase import OsipiBase |
| 10 | + |
| 11 | +# --------------------- Helper Functions --------------------- # |
| 12 | + |
| 13 | +def read_nifti_file(input_file): |
| 14 | + nifti_img = nib.load(input_file) |
| 15 | + return nifti_img.get_fdata(), nifti_img.affine, nifti_img.header |
| 16 | + |
| 17 | +def read_bval_file(bval_file): |
| 18 | + return np.genfromtxt(bval_file, dtype=float) |
| 19 | + |
| 20 | +def read_bvec_file(bvec_file): |
| 21 | + bvec_data = np.genfromtxt(bvec_file) |
| 22 | + return np.transpose(bvec_data) |
| 23 | + |
| 24 | +def save_nifti_file(data, affine, output_file): |
| 25 | + output_img = nib.Nifti1Image(data, affine) |
| 26 | + nib.save(output_img, output_file) |
| 27 | + |
| 28 | +def loop_over_first_n_minus_1_dimensions(arr): |
| 29 | + n = arr.ndim |
| 30 | + for idx in np.ndindex(*arr.shape[:n - 1]): |
| 31 | + yield idx, arr[idx].flatten() |
| 32 | + |
| 33 | +def load_config(): |
| 34 | + workflow_dir = os.environ["WORKFLOW_DIR"] |
| 35 | + config_path = os.path.join(workflow_dir, "conf", "conf.json") |
| 36 | + with open(config_path, "r") as f: |
| 37 | + return json.load(f) |
| 38 | + |
| 39 | +# --------------------- Main Execution --------------------- # |
| 40 | +if __name__ == "__main__": |
| 41 | + # Load config |
| 42 | + config = load_config() |
| 43 | + config = config["workflow_form"] |
| 44 | + |
| 45 | + # Kaapana environment variables |
| 46 | + WORKFLOW_DIR = os.environ["WORKFLOW_DIR"] |
| 47 | + OPERATOR_IN_DIR = os.environ["OPERATOR_IN_DIR"] |
| 48 | + OPERATOR_OUT_DIR = os.environ["OPERATOR_OUT_DIR"] |
| 49 | + |
| 50 | + element_input_dir = os.path.join(WORKFLOW_DIR, OPERATOR_IN_DIR) |
| 51 | + element_output_dir = os.path.join(WORKFLOW_DIR, OPERATOR_OUT_DIR) |
| 52 | + os.makedirs(element_output_dir, exist_ok=True) |
| 53 | + |
| 54 | + # Initialize input_file, bvec_file, bval_file to None |
| 55 | + input_file = None |
| 56 | + bvec_file = None |
| 57 | + bval_file = None |
| 58 | + |
| 59 | + # Check upload type |
| 60 | + dicom_or_nifti = config.get("upload_type", "nifti").lower() |
| 61 | + |
| 62 | + if dicom_or_nifti == "nifti": |
| 63 | + # Parse and validate source files |
| 64 | + source_files_kaapana = [f.strip() for f in config.get("source_files").split(",")] |
| 65 | + input_file, bvec_file, bval_file = source_files_kaapana |
| 66 | + |
| 67 | + # Detect by extension |
| 68 | + input_file = next((f for f in source_files_kaapana if f.endswith((".nii", ".nii.gz"))), None) |
| 69 | + bvec_file = next((f for f in source_files_kaapana if f.endswith(".bvec")), None) |
| 70 | + bval_file = next((f for f in source_files_kaapana if f.endswith(".bval")), None) |
| 71 | + |
| 72 | + # Validate presence |
| 73 | + if not input_file or not bvec_file or not bval_file: |
| 74 | + raise ValueError( |
| 75 | + f"Expected files to include one NIfTI (.nii/.nii.gz), one .bvec, and one .bval, " |
| 76 | + f"but got: {source_files_kaapana}" |
| 77 | + ) |
| 78 | + |
| 79 | + input_file = os.path.join(element_input_dir, input_file) |
| 80 | + bvec_file = os.path.join(element_input_dir, bvec_file) |
| 81 | + bval_file = os.path.join(element_input_dir, bval_file) |
| 82 | + |
| 83 | + else: |
| 84 | + # DICOM case → follow batch structure |
| 85 | + BATCH_DIR = os.path.join(WORKFLOW_DIR, "batch") |
| 86 | + batch_folders = sorted([f for f in glob.glob(os.path.join(BATCH_DIR, "*"))]) |
| 87 | + print(f"batch-folders - {batch_folders}") |
| 88 | + |
| 89 | + if not batch_folders: |
| 90 | + raise FileNotFoundError(f"No batch folders found in {BATCH_DIR}") |
| 91 | + |
| 92 | + # Pick the first batch folder (usually one per patient/series) |
| 93 | + batch_input_dir = os.path.join(batch_folders[0], "dicom_to_nifti") |
| 94 | + |
| 95 | + nifti_files = sorted(glob.glob(os.path.join(batch_input_dir, "*.nii.gz"))) |
| 96 | + if not nifti_files: |
| 97 | + raise FileNotFoundError(f"No NIfTI files found in {batch_input_dir}") |
| 98 | + |
| 99 | + paired_files = [] |
| 100 | + for nifti in nifti_files: |
| 101 | + base = os.path.splitext(os.path.splitext(os.path.basename(nifti))[0])[0] # remove .nii.gz |
| 102 | + bvec_file = os.path.join(batch_input_dir, f"{base}.bvec") |
| 103 | + bval_file = os.path.join(batch_input_dir, f"{base}.bval") |
| 104 | + if os.path.exists(bvec_file) and os.path.exists(bval_file): |
| 105 | + paired_files.append((nifti, bvec_file, bval_file)) |
| 106 | + else: |
| 107 | + raise FileNotFoundError(f"Missing bvec/bval for {nifti}") |
| 108 | + |
| 109 | + # Use the first matched trio |
| 110 | + input_file, bvec_file, bval_file = paired_files[0] |
| 111 | + |
| 112 | + print(f"Using DICOM-converted files from {batch_input_dir}:\n" |
| 113 | + f" {input_file}\n {bvec_file}\n {bval_file}") |
| 114 | + |
| 115 | + # Optional config values |
| 116 | + affine_override = config.get("affine", None) |
| 117 | + algorithm = config.get("algorithm", "OJ_GU_seg") |
| 118 | + algorithm_args = config.get("algorithm_args", None) |
| 119 | + |
| 120 | + # Load input data |
| 121 | + data, affine, _ = read_nifti_file(input_file) |
| 122 | + bvecs = read_bvec_file(bvec_file) |
| 123 | + bvals = read_bval_file(bval_file) |
| 124 | + |
| 125 | + # Override affine if provided |
| 126 | + if affine_override: |
| 127 | + affine = np.array(affine_override).reshape(4, 4) |
| 128 | + |
| 129 | + # Initialize model |
| 130 | + fit = OsipiBase(algorithm=algorithm) |
| 131 | + |
| 132 | + # Preallocate output arrays |
| 133 | + shape = data.shape[:data.ndim - 1] |
| 134 | + f_image = np.zeros(shape, dtype=np.float32) |
| 135 | + Dp_image = np.zeros(shape, dtype=np.float32) |
| 136 | + D_image = np.zeros(shape, dtype=np.float32) |
| 137 | + |
| 138 | + total_iteration = np.prod(shape) |
| 139 | + |
| 140 | + # Fit IVIM model voxel by voxel |
| 141 | + for idx, view in tqdm( |
| 142 | + loop_over_first_n_minus_1_dimensions(data), |
| 143 | + desc="Fitting IVIM model", dynamic_ncols=True, total=total_iteration |
| 144 | + ): |
| 145 | + fit_result = fit.osipi_fit(view, bvals) |
| 146 | + f_image[idx] = fit_result["f"] |
| 147 | + Dp_image[idx] = fit_result["Dp"] |
| 148 | + D_image[idx] = fit_result["D"] |
| 149 | + |
| 150 | + # Save outputs |
| 151 | + save_nifti_file(f_image, affine, os.path.join(element_output_dir, "f.nii.gz")) |
| 152 | + save_nifti_file(Dp_image, affine, os.path.join(element_output_dir, "dp.nii.gz")) |
| 153 | + save_nifti_file(D_image, affine, os.path.join(element_output_dir, "d.nii.gz")) |
| 154 | + |
| 155 | + # Copy all .nii.gz from input directory to WORKFLOW_DIR (Kaapana workaround) |
| 156 | + nii_files = glob.glob(os.path.join(element_input_dir, "*.nii.gz")) |
| 157 | + for nii_file in nii_files: |
| 158 | + shutil.copy(nii_file, WORKFLOW_DIR) |
| 159 | + print(f"Copied {nii_file} to {WORKFLOW_DIR}") |
| 160 | + |
0 commit comments