|
| 1 | +"""Group all npz in one unique file""" |
| 2 | + |
| 3 | + |
| 4 | +import os |
| 5 | +from scipy.sparse import load_npz, vstack, save_npz |
| 6 | +from tqdm import tqdm |
| 7 | +import argparse |
| 8 | +import gc |
| 9 | +import re |
| 10 | +import numpy as np |
| 11 | + |
| 12 | + |
| 13 | + |
| 14 | +def consolidate_chunks(folder_path, chunk_prefix, output_file): |
| 15 | + """ |
| 16 | + Consolidate multiple sparse chunk files into a single sparse .npz file. |
| 17 | + |
| 18 | + Args: |
| 19 | + folder_path (str): Path to the folder containing chunk files. |
| 20 | + chunk_prefix (str): Prefix of the chunk files (e.g., 'masks_chunk', 'masks_cells_chunk'). |
| 21 | + output_file (str): Path to save the consolidated .npz file. |
| 22 | + """ |
| 23 | + print(f"\n-> Consolidating chunks with prefix '{chunk_prefix}' in {folder_path}...") |
| 24 | + |
| 25 | + # Collect all chunk files matching the prefix |
| 26 | + chunk_files = sorted( |
| 27 | + [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.startswith(chunk_prefix) and f.endswith(".npz")] |
| 28 | + ) |
| 29 | + |
| 30 | + if not chunk_files: |
| 31 | + print(f"No chunks found with prefix '{chunk_prefix}'. Skipping.") |
| 32 | + return |
| 33 | + |
| 34 | + # Extract chunk indices and sort numerically |
| 35 | + def extract_index(file_name): |
| 36 | + match = re.search(rf"{chunk_prefix}_(\d+)\.npz$", file_name) |
| 37 | + return int(match.group(1)) if match else float('inf') |
| 38 | + |
| 39 | + chunk_files = sorted(chunk_files, key=lambda x: extract_index(os.path.basename(x))) |
| 40 | + |
| 41 | + # Load and combine all sparse chunks |
| 42 | + sparse_matrices = [] |
| 43 | + for chunk_file in tqdm(chunk_files, desc=f"Loading {chunk_prefix}", unit="chunk"): |
| 44 | + sparse_chunk = load_npz(chunk_file) |
| 45 | + sparse_matrices.append(sparse_chunk) |
| 46 | + del sparse_chunk # Release memory |
| 47 | + gc.collect() |
| 48 | + |
| 49 | + # Combine into a single sparse matrix |
| 50 | + print(f"-> Combining {len(sparse_matrices)} chunks...") |
| 51 | + final_sparse_matrix = vstack(sparse_matrices) |
| 52 | + |
| 53 | + # Save the combined sparse matrix |
| 54 | + print(f"-> Saving...") |
| 55 | + save_npz(output_file, final_sparse_matrix) |
| 56 | + |
| 57 | + # # Ensure the output file is saved |
| 58 | + # if os.path.exists(output_file): |
| 59 | + # # If the file is saved successfully, delete all chunk files |
| 60 | + # print(f"-> Deleting chunk files after successful save...") |
| 61 | + # for chunk_file in chunk_files: |
| 62 | + # os.remove(chunk_file) |
| 63 | + # print(f" - Deleted {chunk_file}") |
| 64 | + # else: |
| 65 | + # print(f"-> Warning: Output file '{output_file}' was not created. Chunk files retained.") |
| 66 | + |
| 67 | + # Cleanup |
| 68 | + del sparse_matrices, final_sparse_matrix |
| 69 | + gc.collect() |
| 70 | + |
| 71 | + print(f"Done.") |
| 72 | + |
| 73 | + |
| 74 | + |
| 75 | +def consolidate_npy_chunks(folder_path, file_prefix, output_file): |
| 76 | + """ |
| 77 | + Consolidate multiple .npy chunk files into a single .npy file. |
| 78 | + |
| 79 | + Args: |
| 80 | + folder_path (str): Path to the folder containing chunk files. |
| 81 | + file_prefix (str): Prefix of the chunk files (e.g., 'images_chunk'). |
| 82 | + output_file (str): Path to save the consolidated .npy file. |
| 83 | + """ |
| 84 | + print(f"\n-> Consolidating .npy chunks with prefix '{file_prefix}' in {folder_path}...") |
| 85 | + |
| 86 | + # Collect all .npy chunk files matching the prefix |
| 87 | + chunk_files = sorted( |
| 88 | + [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.startswith(file_prefix) and f.endswith(".npy")], |
| 89 | + key=lambda x: int(re.search(rf"{file_prefix}_(\d+)\.npy$", os.path.basename(x)).group(1)) |
| 90 | + ) |
| 91 | + |
| 92 | + if not chunk_files: |
| 93 | + print(f"No .npy chunks found with prefix '{file_prefix}'. Skipping.") |
| 94 | + return |
| 95 | + |
| 96 | + # Load and combine all chunks |
| 97 | + arrays = [] |
| 98 | + for chunk_file in tqdm(chunk_files, desc=f"Loading {file_prefix}", unit="chunk"): |
| 99 | + arrays.append(np.load(chunk_file)) |
| 100 | + |
| 101 | + # Concatenate and save the final array |
| 102 | + final_array = np.concatenate(arrays, axis=0) |
| 103 | + np.save(output_file, final_array) |
| 104 | + |
| 105 | + # # Ensure the output file is saved before deleting chunks |
| 106 | + # if os.path.exists(output_file): |
| 107 | + # print(f"-> Deleting chunk files after successful save...") |
| 108 | + # for chunk_file in chunk_files: |
| 109 | + # os.remove(chunk_file) |
| 110 | + # print(f" - Deleted {chunk_file}") |
| 111 | + # else: |
| 112 | + # print(f"-> Warning: Output file '{output_file}' was not created. Chunk files retained.") |
| 113 | + |
| 114 | + # Cleanup |
| 115 | + del arrays, final_array |
| 116 | + gc.collect() |
| 117 | + |
| 118 | + print(f"Done.") |
| 119 | + |
| 120 | + |
| 121 | + |
| 122 | + |
| 123 | +def consolidate_nested_chunks(folder_path, chunk_prefix, output_file): |
| 124 | + """ |
| 125 | + Consolidate nested sparse chunk files into a single sparse .npz file. |
| 126 | + |
| 127 | + Args: |
| 128 | + folder_path (str): Path to the folder containing chunk files. |
| 129 | + chunk_prefix (str): Prefix of the chunk files (e.g., 'masks_chunk'). |
| 130 | + output_file (str): Path to save the consolidated .npz file. |
| 131 | + """ |
| 132 | + print(f"\n-> Consolidating nested chunks with prefix '{chunk_prefix}' in {folder_path}...") |
| 133 | + |
| 134 | + # Collect all nested chunk files matching the prefix |
| 135 | + nested_chunk_files = sorted( |
| 136 | + [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.startswith(chunk_prefix) and f.endswith(".npz")] |
| 137 | + ) |
| 138 | + |
| 139 | + if not nested_chunk_files: |
| 140 | + print(f"No nested chunks found with prefix '{chunk_prefix}'. Skipping.") |
| 141 | + return |
| 142 | + |
| 143 | + # Group by "i" and then by "j" |
| 144 | + def extract_indices(file_name): |
| 145 | + match = re.search(rf"{chunk_prefix}_(\d+)_chunk_(\d+)\.npz$", file_name) |
| 146 | + if match: |
| 147 | + return int(match.group(1)), int(match.group(2)) |
| 148 | + return float('inf'), float('inf') |
| 149 | + |
| 150 | + nested_chunk_files = sorted(nested_chunk_files, key=lambda x: extract_indices(os.path.basename(x))) |
| 151 | + |
| 152 | + # Combine all nested sparse chunks |
| 153 | + sparse_matrices = [] |
| 154 | + for nested_chunk_file in tqdm(nested_chunk_files, desc=f"Loading {chunk_prefix}", unit="nested_chunk"): |
| 155 | + sparse_chunk = load_npz(nested_chunk_file) |
| 156 | + sparse_matrices.append(sparse_chunk) |
| 157 | + |
| 158 | + # Combine into a single sparse matrix |
| 159 | + print(f"-> Combining {len(sparse_matrices)} nested chunks...") |
| 160 | + final_sparse_matrix = vstack(sparse_matrices) |
| 161 | + |
| 162 | + # Save the combined sparse matrix |
| 163 | + print(f"-> Saving...") |
| 164 | + save_npz(output_file, final_sparse_matrix) |
| 165 | + |
| 166 | + # # Ensure the output file is saved before deleting chunks |
| 167 | + # if os.path.exists(output_file): |
| 168 | + # print(f"-> Deleting nested chunk files after successful save...") |
| 169 | + # for nested_chunk_file in nested_chunk_files: |
| 170 | + # os.remove(nested_chunk_file) |
| 171 | + # print(f" - Deleted {nested_chunk_file}") |
| 172 | + # else: |
| 173 | + # print(f"-> Warning: Output file '{output_file}' was not created. Nested chunk files retained.") |
| 174 | + |
| 175 | + # Cleanup |
| 176 | + del sparse_matrices, final_sparse_matrix |
| 177 | + gc.collect() |
| 178 | + |
| 179 | + print(f"Done.") |
| 180 | + |
| 181 | + |
| 182 | + |
| 183 | + |
| 184 | +def process_slide_folders(slide_ids, folder_name): |
| 185 | + """ |
| 186 | + Process all slide folders to consolidate sparse mask chunks into single .npz files. |
| 187 | + |
| 188 | + Args: |
| 189 | + slide_ids (list): List of slide IDs to process. |
| 190 | + folder_name (str): Path to the parent folder containing slide subfolders. |
| 191 | + """ |
| 192 | + for slide_id in slide_ids: |
| 193 | + print(f"\n===== PROCESSING SLIDE: {slide_id} =====") |
| 194 | + slide_folder = os.path.join(folder_name, slide_id) |
| 195 | + |
| 196 | + if not os.path.exists(slide_folder): |
| 197 | + print(f"Slide folder '{slide_folder}' does not exist. Skipping.") |
| 198 | + continue |
| 199 | + |
| 200 | + # Check for images.npy or chunked images |
| 201 | + images_file = os.path.join(slide_folder, "images.npy") |
| 202 | + chunked_images = sorted( |
| 203 | + [os.path.join(slide_folder, f) for f in os.listdir(slide_folder) if f.startswith("images_chunk") and f.endswith(".npy")] |
| 204 | + ) |
| 205 | + |
| 206 | + if os.path.exists(images_file): |
| 207 | + print(f"[INFO] Single 'images.npy' file detected for slide {slide_id}.") |
| 208 | + consolidate_chunks(slide_folder, "masks_chunk", os.path.join(slide_folder, "masks.npz")) |
| 209 | + consolidate_chunks(slide_folder, "masks_cells_chunk", os.path.join(slide_folder, "masks_cells.npz")) |
| 210 | + elif chunked_images: |
| 211 | + print(f"[INFO] Chunked 'images_chunk' files detected for slide {slide_id}.") |
| 212 | + consolidate_npy_chunks(slide_folder, "images_chunk", os.path.join(slide_folder, "images.npy")) |
| 213 | + consolidate_npy_chunks(slide_folder, "types_chunk", os.path.join(slide_folder, "types.npy")) |
| 214 | + consolidate_npy_chunks(slide_folder, "patch_ids_chunk", os.path.join(slide_folder, "patch_ids.npy")) |
| 215 | + consolidate_nested_chunks(slide_folder, "masks_chunk", os.path.join(slide_folder, "masks.npz")) |
| 216 | + consolidate_nested_chunks(slide_folder, "masks_cells_chunk", os.path.join(slide_folder, "masks_cells.npz")) |
| 217 | + |
| 218 | + print("\nAll slides processed successfully.") |
| 219 | + |
| 220 | + |
| 221 | + |
| 222 | + |
| 223 | +if __name__ == "__main__": |
| 224 | + parser = argparse.ArgumentParser(description="Consolidate sparse mask chunks for multiple slides.") |
| 225 | + |
| 226 | + # Input arguments |
| 227 | + parser.add_argument("--slide_ids", type=str, nargs="+", required=True, help="List of slide IDs to process.") |
| 228 | + parser.add_argument("--folder_name", type=str, default="/Volumes/DD_FGS/MICS/data_HE2CellType/CT_DS/check_align_patches/patches_xenium", help="Parent folder containing slide subfolders.") |
| 229 | + |
| 230 | + args = parser.parse_args() |
| 231 | + |
| 232 | + # Run the consolidation process |
| 233 | + process_slide_folders(args.slide_ids, args.folder_name) |
0 commit comments