├── ASA_Pretrain ├── dataloaders │ ├── __init__.py │ ├── dataloader_default.py │ └── dataloader_hog.py ├── engine_for_pretraining │ ├── __init__.py │ ├── engine_default.py │ └── engine_hog.py ├── hog_feature │ ├── create_hog_feature.py │ └── vhog3d.py ├── model │ ├── __init__.py │ └── model_DEFAULT.py ├── requirements.txt ├── tools │ ├── dist_train.sh │ └── train.py └── utils │ ├── __init__.py │ ├── optim_factory.py │ └── util.py ├── ASA_Segmentation ├── ACDC_dice │ └── inference.py ├── BraTS_dice │ ├── inference.py │ ├── inference_IBSR.py │ └── inference_WMH.py ├── Synapse_dice_and_hd │ ├── inference.py │ └── inferencehd.py ├── __init__.py ├── configuration.py ├── dataset_conversion │ ├── Task777_MAE.py │ ├── Task999_BraTS_2021.py │ ├── __init__.py │ └── utils.py ├── dataset_json │ ├── ACDC_dataset.json │ └── Synapse.json ├── evaluation │ ├── __init__.py │ ├── add_dummy_task_with_mean_over_all_tasks.py │ ├── add_mean_dice_to_json.py │ ├── collect_results_files.py │ ├── evaluator.py │ ├── metrics.py │ ├── model_selection │ │ ├── __init__.py │ │ ├── collect_all_fold0_results_and_summarize_in_one_csv.py │ │ ├── ensemble.py │ │ ├── figure_out_what_to_submit.py │ │ ├── rank_candidates.py │ │ ├── rank_candidates_StructSeg.py │ │ ├── rank_candidates_cascade.py │ │ ├── summarize_results_in_one_json.py │ │ └── summarize_results_with_plans.py │ ├── region_based_evaluation.py │ └── surface_dice.py ├── experiment_planning │ ├── DatasetAnalyzer.py │ ├── __init__.py │ ├── alternative_experiment_planning │ │ ├── experiment_planner_baseline_3DUNet_v21_11GB.py │ │ ├── experiment_planner_baseline_3DUNet_v21_16GB.py │ │ ├── experiment_planner_baseline_3DUNet_v21_32GB.py │ │ ├── experiment_planner_baseline_3DUNet_v21_3convperstage.py │ │ ├── experiment_planner_baseline_3DUNet_v22.py │ │ ├── experiment_planner_baseline_3DUNet_v23.py │ │ ├── experiment_planner_residual_3DUNet_v21.py │ │ ├── normalization │ │ │ ├── experiment_planner_2DUNet_v21_RGB_scaleto_0_1.py │ │ │ ├── experiment_planner_3DUNet_CT2.py │ │ │ └── experiment_planner_3DUNet_nonCT.py │ │ ├── patch_size │ │ │ ├── experiment_planner_3DUNet_isotropic_in_mm.py │ │ │ └── experiment_planner_3DUNet_isotropic_in_voxels.py │ │ ├── pooling_and_convs │ │ │ ├── experiment_planner_baseline_3DUNet_allConv3x3.py │ │ │ └── experiment_planner_baseline_3DUNet_poolBasedOnSpacing.py │ │ └── target_spacing │ │ │ ├── experiment_planner_baseline_3DUNet_targetSpacingForAnisoAxis.py │ │ │ ├── experiment_planner_baseline_3DUNet_v21_customTargetSpacing_2x2x2.py │ │ │ └── experiment_planner_baseline_3DUNet_v21_noResampling.py │ ├── change_batch_size.py │ ├── common_utils.py │ ├── experiment_planner_baseline_2DUNet.py │ ├── experiment_planner_baseline_2DUNet_v21.py │ ├── experiment_planner_baseline_3DUNet.py │ ├── experiment_planner_baseline_3DUNet_v21.py │ ├── nnFormer_convert_decathlon_task.py │ ├── nnFormer_plan_and_preprocess.py │ ├── nnFormer_plan_and_preprocess_noLabel.py │ ├── old │ │ └── old_plan_and_preprocess_task.py │ ├── summarize_plans.py │ └── utils.py ├── get_pretrain_ade.py ├── inference │ ├── __init__.py │ ├── change_trainer.py │ ├── ensemble_predictions.py │ ├── inferTs │ │ └── swin_nomask_2 │ │ │ └── plans.pkl │ ├── predict.py │ ├── predict_simple.py │ ├── pretrained_models │ │ ├── __init__.py │ │ ├── change_trainer.py │ │ ├── collect_pretrained_models.py │ │ ├── download_pretrained_model.py │ │ ├── ensemble_predictions.py │ │ ├── predict.py │ │ ├── predict_simple.py │ │ └── segmentation_export.py │ └── segmentation_export.py ├── network_architecture │ ├── MEDIUMVIT.py │ ├── Swin_Unet_l_gelunorm.py │ ├── Swin_Unet_s_ACDC_2laterdown.py │ ├── __init__.py │ ├── generic_UNet.py │ ├── initialization.py │ └── neural_network.py ├── paths.py ├── postprocessing │ ├── connected_components.py │ ├── consolidate_all_for_paper.py │ ├── consolidate_postprocessing.py │ └── consolidate_postprocessing_simple.py ├── preprocessing │ ├── cropping.py │ ├── custom_preprocessors │ │ └── preprocessor_scale_RGB_to_0_1.py │ ├── preprocessing.py │ └── sanity_checks.py ├── run │ ├── __init__.py │ ├── default_configuration.py │ ├── load_pretrained_weights.py │ ├── run_training.py │ ├── run_training_DDP.py │ └── run_training_DP.py ├── training │ ├── __init__.py │ ├── cascade_stuff │ │ ├── __init__.py │ │ └── predict_next_stage.py │ ├── data_augmentation │ │ ├── __init__.py │ │ ├── custom_transforms.py │ │ ├── data_augmentation_insaneDA.py │ │ ├── data_augmentation_insaneDA2.py │ │ ├── data_augmentation_moreDA.py │ │ ├── data_augmentation_moreDA_SYM.py │ │ ├── data_augmentation_noDA.py │ │ ├── default_data_augmentation.py │ │ ├── downsampling.py │ │ └── pyramid_augmentations.py │ ├── dataloading │ │ ├── __init__.py │ │ ├── dataset_loading.py │ │ ├── dataset_loading_sym.py │ │ └── dataset_loading_sym_debug.py │ ├── learning_rate │ │ └── poly_lr.py │ ├── loss_functions │ │ ├── TopK_loss.py │ │ ├── __init__.py │ │ ├── crossentropy.py │ │ ├── deep_supervision.py │ │ └── dice_loss.py │ ├── model_restore.py │ ├── network_training │ │ ├── network_trainer.py │ │ ├── network_trainer_synapse.py │ │ ├── nnFormerTrainer.py │ │ ├── nnFormerTrainerCascadeFullRes.py │ │ ├── nnFormerTrainerV2.py │ │ ├── nnFormerTrainerV2_ACDC.py │ │ ├── nnFormerTrainerV2_BraTS.py │ │ ├── nnFormerTrainerV2_CascadeFullRes.py │ │ ├── nnFormerTrainerV2_MEDIUMVIT_MAE.py │ │ ├── nnFormerTrainerV2_Synapse.py │ │ └── nnFormerTrainer_synapse.py │ └── optimizer │ │ └── ranger.py └── utilities │ ├── __init__.py │ ├── distributed.py │ ├── file_conversions.py │ ├── file_endings.py │ ├── folder_names.py │ ├── nd_softmax.py │ ├── one_hot_encoding.py │ ├── overlay_plots.py │ ├── random_stuff.py │ ├── recursive_delete_npz.py │ ├── recursive_rename_taskXX_to_taskXXX.py │ ├── sitk_stuff.py │ ├── task_name_id_conversion.py │ ├── tensor_utilities.py │ └── to_torch.py ├── LICENSE └── README.md /ASA_Pretrain/dataloaders/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lhaof/ASA/1f6295030d9370e23964ac4a3903ccedfb2315a9/ASA_Pretrain/dataloaders/__init__.py -------------------------------------------------------------------------------- /ASA_Pretrain/engine_for_pretraining/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lhaof/ASA/1f6295030d9370e23964ac4a3903ccedfb2315a9/ASA_Pretrain/engine_for_pretraining/__init__.py -------------------------------------------------------------------------------- /ASA_Pretrain/engine_for_pretraining/engine_default.py: -------------------------------------------------------------------------------- 1 | # -------------------------------------------------------- 2 | # Based on BEiT, timm, DINO and DeiT code bases 3 | # https://github.com/microsoft/unilm/tree/master/beit 4 | # https://github.com/rwightman/pytorch-image-models/tree/master/timm 5 | # https://github.com/facebookresearch/deit 6 | # https://github.com/facebookresearch/dino 7 | # --------------------------------------------------------' 8 | import math 9 | import sys 10 | from typing import Iterable 11 | 12 | import torch 13 | import torch.nn as nn 14 | 15 | import utils.util as util 16 | from einops import rearrange 17 | from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD 18 | 19 | 20 | def train_one_epoch(model: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, 21 | device: torch.device, epoch: int, loss_scaler, max_norm: float = 0, patch_size: int = 16, 22 | log_writer=None, lr_scheduler=None, start_steps=None, 23 | lr_schedule_values=None, wd_schedule_values=None): 24 | model.train() 25 | metric_logger = util.MetricLogger(delimiter=" ") 26 | metric_logger.add_meter('lr', util.SmoothedValue(window_size=1, fmt='{value:.6f}')) 27 | metric_logger.add_meter('min_lr', util.SmoothedValue(window_size=1, fmt='{value:.6f}')) 28 | header = 'Epoch: [{}]'.format(epoch) 29 | print_freq = 10 30 | 31 | loss_func = nn.MSELoss() 32 | 33 | for step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)): 34 | # assign learning rate & weight decay for each step 35 | it = start_steps + step # global training iteration 36 | if lr_schedule_values is not None or wd_schedule_values is not None: 37 | for i, param_group in enumerate(optimizer.param_groups): 38 | if lr_schedule_values is not None: 39 | param_group["lr"] = lr_schedule_values[it] * param_group["lr_scale"] 40 | if wd_schedule_values is not None and param_group["weight_decay"] > 0: 41 | param_group["weight_decay"] = wd_schedule_values[it] 42 | 43 | images, bool_masked_pos = batch['data'], batch['mask'] 44 | images = images.to(device, non_blocking=True) 45 | bool_masked_pos = bool_masked_pos.to(device, non_blocking=True).flatten(1).to(torch.bool) 46 | 47 | # import pdb; pdb.set_trace() 48 | with torch.no_grad(): 49 | images_patch = rearrange(images, 'b c (h p1) (w p2) (s p3)-> b (h w s) (p1 p2 p3 c)', p1=patch_size, 50 | p2=patch_size, p3=patch_size) 51 | 52 | B, _, C = images_patch.shape 53 | labels = images_patch[bool_masked_pos].reshape(B, -1, C) 54 | 55 | with torch.cuda.amp.autocast(): 56 | outputs = model(images, bool_masked_pos) 57 | loss = loss_func(input=outputs, target=labels) 58 | 59 | loss_value = loss.item() 60 | 61 | if not math.isfinite(loss_value): 62 | print("Loss is {}, stopping training".format(loss_value)) 63 | sys.exit(1) 64 | 65 | optimizer.zero_grad() 66 | # this attribute is added by timm on one optimizer (adahessian) 67 | is_second_order = hasattr(optimizer, 'is_second_order') and optimizer.is_second_order 68 | grad_norm = loss_scaler(loss, optimizer, clip_grad=max_norm, 69 | parameters=model.parameters(), create_graph=is_second_order) 70 | loss_scale_value = loss_scaler.state_dict()["scale"] 71 | 72 | torch.cuda.synchronize() 73 | 74 | metric_logger.update(loss=loss_value) 75 | metric_logger.update(loss_scale=loss_scale_value) 76 | min_lr = 10. 77 | max_lr = 0. 78 | for group in optimizer.param_groups: 79 | min_lr = min(min_lr, group["lr"]) 80 | max_lr = max(max_lr, group["lr"]) 81 | 82 | metric_logger.update(lr=max_lr) 83 | metric_logger.update(min_lr=min_lr) 84 | weight_decay_value = None 85 | for group in optimizer.param_groups: 86 | if group["weight_decay"] > 0: 87 | weight_decay_value = group["weight_decay"] 88 | metric_logger.update(weight_decay=weight_decay_value) 89 | metric_logger.update(grad_norm=grad_norm) 90 | 91 | if log_writer is not None: 92 | log_writer.update(loss=loss_value, head="loss") 93 | log_writer.update(loss_scale=loss_scale_value, head="opt") 94 | log_writer.update(lr=max_lr, head="opt") 95 | log_writer.update(min_lr=min_lr, head="opt") 96 | log_writer.update(weight_decay=weight_decay_value, head="opt") 97 | log_writer.update(grad_norm=grad_norm, head="opt") 98 | 99 | log_writer.set_step() 100 | 101 | if lr_scheduler is not None: 102 | lr_scheduler.step_update(start_steps + step) 103 | # gather the stats from all processes 104 | metric_logger.synchronize_between_processes() 105 | print("Averaged stats:", metric_logger) 106 | return {k: meter.global_avg for k, meter in metric_logger.meters.items()} 107 | 108 | 109 | def eval_one_epoch(model: torch.nn.Module, data_loader: Iterable, device: torch.device, epoch: int, patch_size): 110 | model.eval() 111 | metric_logger = util.MetricLogger(delimiter=" ") 112 | print_freq = len(data_loader) 113 | loss_func = nn.MSELoss() 114 | header = 'Epoch: [{}]'.format(epoch) 115 | for step, batch in enumerate(metric_logger.log_every(data_loader, print_freq, header)): 116 | images, bool_masked_pos = batch['data'], batch['mask'] 117 | images = images.to(device, non_blocking=True) 118 | bool_masked_pos = bool_masked_pos.to(device, non_blocking=True).flatten(1).to(torch.bool) 119 | 120 | with torch.no_grad(): 121 | images_patch = rearrange(images, 'b c (h p1) (w p2) (s p3)-> b (h w s) (p1 p2 p3 c)', p1=patch_size, p2=patch_size, p3=patch_size) 122 | 123 | B, _, C = images_patch.shape 124 | labels = images_patch[bool_masked_pos].reshape(B, -1, C) 125 | 126 | with torch.cuda.amp.autocast(): 127 | outputs = model(images, bool_masked_pos) 128 | loss = loss_func(input=outputs, target=labels) 129 | 130 | loss_value = loss.item() 131 | metric_logger.update(loss=loss_value) 132 | metric_logger.synchronize_between_processes() 133 | print("Averaged stats:", metric_logger) 134 | return {k: meter.global_avg for k, meter in metric_logger.meters.items()} 135 | -------------------------------------------------------------------------------- /ASA_Pretrain/hog_feature/create_hog_feature.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | import numpy as np 4 | import scipy.ndimage 5 | import matplotlib.pyplot as plt 6 | import matplotlib.image as mpimg 7 | 8 | from skimage.feature import hog 9 | from skimage import data, color, exposure 10 | from vhog3d import vhog3d 11 | import SimpleITK as sitk 12 | from batchgenerators.utilities.file_and_folder_operations import * 13 | import threading 14 | from multiprocessing import Pool, cpu_count 15 | import time 16 | import random 17 | 18 | 19 | def normalization(data): 20 | _range = np.max(data) - np.min(data) 21 | return (data - np.min(data)) / _range 22 | 23 | 24 | def _hog_normalize_block(block, method, eps=1e-5): 25 | if method == 'L1': 26 | out = block / (np.sum(np.abs(block)) + eps) 27 | elif method == 'L1-sqrt': 28 | out = np.sqrt(block / (np.sum(np.abs(block)) + eps)) 29 | elif method == 'L2': 30 | out = block / np.sqrt(np.sum(block ** 2) + eps ** 2) 31 | elif method == 'L2-Hys': 32 | out = block / np.sqrt(np.sum(block ** 2) + eps ** 2) 33 | out = np.minimum(out, 0.2) 34 | out = out / np.sqrt(np.sum(out ** 2) + eps ** 2) 35 | else: 36 | raise ValueError('Selected block normalization method is invalid.') 37 | 38 | return out 39 | 40 | 41 | def vhog3d_cal(arg): 42 | for sub in arg: 43 | time_now = time.time() 44 | # if sub in sub_list_exist: 45 | # print("Jumping ", sub) 46 | # continue 47 | image = np.load(join(DATA_FILE, sub))["data"] 48 | image = normalization(image[0]) 49 | grad_vec = vhog3d(image, cell_size, block_size, theta_histogram_bins, phi_histogram_bins, visulize=False) 50 | np.savez(join(HOG_SAVE, sub), data=grad_vec) 51 | 52 | print("Handling ", sub, " Time:", time.time() - time_now) 53 | # print(arg) 54 | # for sub in arg[0]: 55 | # print(sub) 56 | 57 | 58 | if __name__ == "__main__": 59 | print(cpu_count()) 60 | # p = Pool(60) 61 | # length = int(len(sub_list) / 60) 62 | # for i in range(60): 63 | # if i == 59: 64 | # sub_thr = sub_list[i * length:] 65 | # else: 66 | # sub_thr = sub_list[i * length:i * length + length] 67 | # t = p.apply_async(vhog3d_cal, args=(sub_thr,)) 68 | # p.close() 69 | # p.join() 70 | 71 | image = np.load( 72 | "Data Path/DATA_AFTERTRANS/sub-ADNI002S0619_ses-M06.npz")[ 73 | "data"] 74 | image = normalization(image) 75 | for k in [20, 40, 50, 60, 70, 80, 100]: 76 | img = image[0, k, ::] 77 | fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 8), sharex=True, sharey=True) 78 | # 79 | ax1.axis('off') 80 | ax1.imshow(img, cmap='gray') 81 | ax1.set_title('Input image') 82 | fd, hog_image = hog(img, orientations=9, pixels_per_cell=(8, 8), 83 | cells_per_block=(16, 16), visualize=True) 84 | # 85 | region = 128 86 | for i in range(16): 87 | for j in range(16): 88 | hog_image[i * region:i * region + region, j * region:j * region + region] = _hog_normalize_block( 89 | hog_image[i * region:i * region + region, j * region:j * region + region], method="L2") 90 | # 91 | hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02)) 92 | # # 93 | ax2.axis('off') 94 | ax2.imshow(hog_image_rescaled, cmap=plt.cm.gray) 95 | ax2.set_title('Histogram of Oriented Gradients') 96 | plt.show() 97 | 98 | plt.imshow(hog_image_rescaled, cmap='gray') 99 | # plt.title('Histogram of Oriented Gradients') 100 | plt.axis('off') 101 | plt.savefig('Save Path/visual_miccai/hog_{}.jpg'.format(k), dpi=400) 102 | plt.show() -------------------------------------------------------------------------------- /ASA_Pretrain/model/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lhaof/ASA/1f6295030d9370e23964ac4a3903ccedfb2315a9/ASA_Pretrain/model/__init__.py -------------------------------------------------------------------------------- /ASA_Pretrain/requirements.txt: -------------------------------------------------------------------------------- 1 | timm==0.4.12 2 | Pillow 3 | blobfile 4 | mypy 5 | numpy 6 | pytest 7 | requests 8 | einops 9 | tensorboardX 10 | # deepspeed==0.4.0 11 | scipy -------------------------------------------------------------------------------- /ASA_Pretrain/tools/dist_train.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | GPUS=$1 4 | PORT=${PORT:-29150} 5 | 6 | 7 | PYTHONPATH="$(dirname $0)/..":$PYTHONPATH\ 8 | OMP_NUM_THREADS=1 python -m torch.distributed.launch --master_port=$PORT \ 9 | --nproc_per_node=$GPUS $(dirname "$0")/train.py -------------------------------------------------------------------------------- /ASA_Pretrain/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lhaof/ASA/1f6295030d9370e23964ac4a3903ccedfb2315a9/ASA_Pretrain/utils/__init__.py -------------------------------------------------------------------------------- /ASA_Segmentation/ACDC_dice/inference.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import SimpleITK as sitk 4 | import numpy as np 5 | from medpy.metric import binary 6 | from sklearn.neighbors import KDTree 7 | from scipy import ndimage 8 | 9 | 10 | def read_nii(path): 11 | itk_img = sitk.ReadImage(path) 12 | spacing = np.array(itk_img.GetSpacing()) 13 | return sitk.GetArrayFromImage(itk_img), spacing 14 | 15 | 16 | def dice(pred, label): 17 | if (pred.sum() + label.sum()) == 0: 18 | return 1 19 | else: 20 | return 2. * np.logical_and(pred, label).sum() / (pred.sum() + label.sum()) 21 | 22 | 23 | def process_label(label): 24 | rv = label == 1 25 | myo = label == 2 26 | lv = label == 3 27 | 28 | return rv, myo, lv 29 | 30 | 31 | ''' 32 | def hd(pred,gt): 33 | pred[pred > 0] = 1 34 | gt[gt > 0] = 1 35 | if pred.sum() > 0 and gt.sum()>0: 36 | dice = binary.dc(pred, gt) 37 | hd95 = binary.hd95(pred, gt) 38 | return dice, hd95 39 | elif pred.sum() > 0 and gt.sum()==0: 40 | return 1, 0 41 | else: 42 | return 0, 0 43 | ''' 44 | 45 | 46 | def hd(pred, gt): 47 | # labelPred=sitk.GetImageFromArray(lP.astype(np.float32), isVector=False) 48 | # labelTrue=sitk.GetImageFromArray(lT.astype(np.float32), isVector=False) 49 | # hausdorffcomputer=sitk.HausdorffDistanceImageFilter() 50 | # hausdorffcomputer.Execute(labelTrue>0.5,labelPred>0.5) 51 | # return hausdorffcomputer.GetAverageHausdorffDistance() 52 | if pred.sum() > 0 and gt.sum() > 0: 53 | hd95 = binary.hd95(pred, gt) 54 | print(hd95) 55 | return hd95 56 | else: 57 | return 0 58 | 59 | 60 | def test(fold): 61 | path = '../DATASET/nnFormer_raw/nnFormer_raw_data/Task001_ACDC/' 62 | label_list = sorted(glob.glob(os.path.join(path, 'labelsTs', '*nii.gz'))) 63 | infer_list = sorted(glob.glob(os.path.join(path, 'inferTs', fold, '*nii.gz'))) 64 | print("loading success...") 65 | print(label_list) 66 | print(infer_list) 67 | Dice_rv = [] 68 | Dice_myo = [] 69 | Dice_lv = [] 70 | 71 | file = path + 'inferTs/' + fold 72 | if not os.path.exists(file): 73 | os.makedirs(file) 74 | fw = open(file + '/dice.txt', 'w') 75 | 76 | for label_path, infer_path in zip(label_list, infer_list): 77 | print(label_path.split('/')[-1]) 78 | print(infer_path.split('/')[-1]) 79 | label, spacing = read_nii(label_path) 80 | infer, spacing = read_nii(infer_path) 81 | label_rv, label_myo, label_lv = process_label(label) 82 | infer_rv, infer_myo, infer_lv = process_label(infer) 83 | 84 | Dice_rv.append(dice(infer_rv, label_rv)) 85 | Dice_myo.append(dice(infer_myo, label_myo)) 86 | Dice_lv.append(dice(infer_lv, label_lv)) 87 | 88 | fw.write('*' * 20 + '\n', ) 89 | fw.write(infer_path.split('/')[-1] + '\n') 90 | 91 | fw.write('*' * 20 + '\n', ) 92 | fw.write(infer_path.split('/')[-1] + '\n') 93 | fw.write('Dice_rv: {:.4f}\n'.format(Dice_rv[-1])) 94 | fw.write('Dice_myo: {:.4f}\n'.format(Dice_myo[-1])) 95 | fw.write('Dice_lv: {:.4f}\n'.format(Dice_lv[-1])) 96 | fw.write('*' * 20 + '\n') 97 | 98 | fw.write('*' * 20 + '\n') 99 | fw.write('Mean_Dice\n') 100 | fw.write('Dice_rv' + str(np.mean(Dice_rv)) + '\n') 101 | fw.write('Dice_myo' + str(np.mean(Dice_myo)) + '\n') 102 | fw.write('Dice_lv' + str(np.mean(Dice_lv)) + '\n') 103 | fw.write('*' * 20 + '\n') 104 | 105 | dsc = [] 106 | dsc.append(np.mean(Dice_rv)) 107 | dsc.append(np.mean(Dice_myo)) 108 | dsc.append(np.mean(Dice_lv)) 109 | 110 | fw.write('DSC:' + str(np.mean(dsc)) + '\n') 111 | print('done') 112 | 113 | 114 | if __name__ == '__main__': 115 | fold = 'output' 116 | test(fold) 117 | -------------------------------------------------------------------------------- /ASA_Segmentation/BraTS_dice/inference.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import SimpleITK as sitk 4 | import numpy as np 5 | from medpy.metric import dc, hd95 6 | from multiprocessing.pool import Pool 7 | from batchgenerators.utilities.file_and_folder_operations import * 8 | import pandas as pd 9 | 10 | 11 | def compute_BraTS_dice(ref, pred): 12 | """ 13 | ref and gt are binary integer numpy.ndarray s 14 | :param ref: 15 | :param gt: 16 | :return: 17 | """ 18 | num_ref = np.sum(ref) 19 | num_pred = np.sum(pred) 20 | 21 | if num_ref == 0: 22 | if num_pred == 0: 23 | return 1 24 | else: 25 | return 0 26 | else: 27 | return dc(pred, ref) 28 | 29 | 30 | def compute_BraTS_HD95(ref, pred): 31 | """ 32 | ref and gt are binary integer numpy.ndarray s 33 | spacing is assumed to be (1, 1, 1) 34 | :param ref: 35 | :param pred: 36 | :return: 37 | """ 38 | num_ref = np.sum(ref) 39 | num_pred = np.sum(pred) 40 | 41 | if num_ref == 0: 42 | if num_pred == 0: 43 | return 0 44 | else: 45 | return 373.12866 46 | elif num_pred == 0 and num_ref != 0: 47 | return 373.12866 48 | else: 49 | return hd95(pred, ref, (1, 1, 1)) 50 | 51 | 52 | def evaluate_BraTS_case(arr: np.ndarray, arr_gt: np.ndarray): 53 | """ 54 | attempting to reimplement the brats evaluation scheme 55 | assumes edema=1, non_enh=2, enh=3 56 | :param arr: 57 | :param arr_gt: 58 | :return: 59 | """ 60 | # whole tumor 61 | mask_gt = (arr_gt != 0).astype(int) 62 | mask_pred = (arr != 0).astype(int) 63 | dc_whole = compute_BraTS_dice(mask_gt, mask_pred) 64 | hd95_whole = compute_BraTS_HD95(mask_gt, mask_pred) 65 | del mask_gt, mask_pred 66 | 67 | # tumor core 68 | mask_gt = (arr_gt > 1).astype(int) 69 | mask_pred = (arr > 1).astype(int) 70 | dc_core = compute_BraTS_dice(mask_gt, mask_pred) 71 | hd95_core = compute_BraTS_HD95(mask_gt, mask_pred) 72 | del mask_gt, mask_pred 73 | 74 | # enhancing 75 | mask_gt = (arr_gt == 3).astype(int) 76 | mask_pred = (arr == 3).astype(int) 77 | dc_enh = compute_BraTS_dice(mask_gt, mask_pred) 78 | hd95_enh = compute_BraTS_HD95(mask_gt, mask_pred) 79 | del mask_gt, mask_pred 80 | 81 | return dc_whole, dc_core, dc_enh, hd95_whole, hd95_core, hd95_enh 82 | 83 | 84 | def load_evaluate(filename_gt: str, filename_pred: str): 85 | arr_pred = sitk.GetArrayFromImage(sitk.ReadImage(filename_pred)) 86 | arr_gt = sitk.GetArrayFromImage(sitk.ReadImage(filename_gt)) 87 | return evaluate_BraTS_case(arr_pred, arr_gt) 88 | 89 | 90 | def evaluate_BraTS_folder(folder_pred, folder_gt, num_processes: int = 24, strict=False): 91 | nii_pred = subfiles(folder_pred, suffix='.nii.gz', join=False) 92 | if len(nii_pred) == 0: 93 | return 94 | nii_gt = subfiles(folder_gt, suffix='.nii.gz', join=False) 95 | assert all([i in nii_gt for i in nii_pred]), 'not all predicted niftis have a reference file!' 96 | if strict: 97 | assert all([i in nii_pred for i in nii_gt]), 'not all gt niftis have a predicted file!' 98 | p = Pool(num_processes) 99 | nii_pred_fullpath = [join(folder_pred, i) for i in nii_pred] 100 | nii_gt_fullpath = [join(folder_gt, i) for i in nii_pred] 101 | results = p.starmap(load_evaluate, zip(nii_gt_fullpath, nii_pred_fullpath)) 102 | # now write to output file 103 | with open(join(folder_pred, 'results.csv'), 'w') as f: 104 | f.write("name,dc_whole,dc_core,dc_enh,hd95_whole,hd95_core,hd95_enh\n") 105 | for fname, r in zip(nii_pred, results): 106 | f.write(fname) 107 | f.write(",%0.4f,%0.4f,%0.4f,%3.3f,%3.3f,%3.3f\n" % r) 108 | 109 | 110 | def main(): 111 | folder_pred = '/data2/huangjunjia/nnFormer/nnFormer_trained_models/nnFormer/3d_fullres/Task999_BraTS2021/Paper/Infers/DEBUG/' 112 | evaluate_BraTS_folder(folder_pred, 113 | '/data2/huangjunjia/nnFormer/nnFormer_raw/nnFormer_raw_data/Task999_BraTS2021/labelsTs') 114 | 115 | result = pd.read_csv(join(folder_pred, 'results.csv'))[ 116 | ['dc_whole', 'dc_core', 'dc_enh', 'hd95_whole', 'hd95_core', 'hd95_enh']] 117 | print(result.mean(axis=0)) 118 | 119 | 120 | if __name__ == '__main__': 121 | main() 122 | -------------------------------------------------------------------------------- /ASA_Segmentation/BraTS_dice/inference_IBSR.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import SimpleITK as sitk 4 | import numpy as np 5 | from medpy.metric import dc, hd95 6 | from multiprocessing.pool import Pool 7 | from batchgenerators.utilities.file_and_folder_operations import * 8 | import pandas as pd 9 | 10 | 11 | def compute_BraTS_dice(ref, pred): 12 | """ 13 | ref and gt are binary integer numpy.ndarray s 14 | :param ref: 15 | :param gt: 16 | :return: 17 | """ 18 | num_ref = np.sum(ref) 19 | num_pred = np.sum(pred) 20 | 21 | if num_ref == 0: 22 | if num_pred == 0: 23 | return 1 24 | else: 25 | return 0 26 | else: 27 | return dc(pred, ref) 28 | 29 | 30 | def compute_BraTS_HD95(ref, pred): 31 | """ 32 | ref and gt are binary integer numpy.ndarray s 33 | spacing is assumed to be (1, 1, 1) 34 | :param ref: 35 | :param pred: 36 | :return: 37 | """ 38 | num_ref = np.sum(ref) 39 | num_pred = np.sum(pred) 40 | 41 | if num_ref == 0: 42 | if num_pred == 0: 43 | return 0 44 | else: 45 | return 373.12866 46 | elif num_pred == 0 and num_ref != 0: 47 | return 373.12866 48 | else: 49 | return hd95(pred, ref, (1, 1, 1)) 50 | 51 | 52 | def evaluate_BraTS_case(arr: np.ndarray, arr_gt: np.ndarray): 53 | """ 54 | attempting to reimplement the brats evaluation scheme 55 | assumes edema=1, non_enh=2, enh=3 56 | :param arr: 57 | :param arr_gt: 58 | :return: 59 | """ 60 | # whole tumor 61 | mask_gt = (arr_gt == 1).astype(int) 62 | mask_pred = (arr == 1).astype(int) 63 | dc_whole = compute_BraTS_dice(mask_gt, mask_pred) 64 | hd95_whole = compute_BraTS_HD95(mask_gt, mask_pred) 65 | del mask_gt, mask_pred 66 | 67 | # tumor core 68 | mask_gt = (arr_gt == 2).astype(int) 69 | mask_pred = (arr == 2).astype(int) 70 | dc_core = compute_BraTS_dice(mask_gt, mask_pred) 71 | hd95_core = compute_BraTS_HD95(mask_gt, mask_pred) 72 | del mask_gt, mask_pred 73 | 74 | # enhancing 75 | mask_gt = (arr_gt == 3).astype(int) 76 | mask_pred = (arr == 3).astype(int) 77 | dc_enh = compute_BraTS_dice(mask_gt, mask_pred) 78 | hd95_enh = compute_BraTS_HD95(mask_gt, mask_pred) 79 | del mask_gt, mask_pred 80 | 81 | return dc_whole, dc_core, dc_enh, hd95_whole, hd95_core, hd95_enh 82 | 83 | 84 | def load_evaluate(filename_gt: str, filename_pred: str): 85 | arr_pred = sitk.GetArrayFromImage(sitk.ReadImage(filename_pred)) 86 | arr_gt = sitk.GetArrayFromImage(sitk.ReadImage(filename_gt)) 87 | return evaluate_BraTS_case(arr_pred, arr_gt) 88 | 89 | 90 | def evaluate_BraTS_folder(folder_pred, folder_gt, num_processes: int = 24, strict=False): 91 | nii_pred = subfiles(folder_pred, suffix='.nii.gz', join=False) 92 | if len(nii_pred) == 0: 93 | return 94 | nii_gt = subfiles(folder_gt, suffix='.nii.gz', join=False) 95 | assert all([i in nii_gt for i in nii_pred]), 'not all predicted niftis have a reference file!' 96 | if strict: 97 | assert all([i in nii_pred for i in nii_gt]), 'not all gt niftis have a predicted file!' 98 | p = Pool(num_processes) 99 | nii_pred_fullpath = [join(folder_pred, i) for i in nii_pred] 100 | nii_gt_fullpath = [join(folder_gt, i) for i in nii_pred] 101 | results = p.starmap(load_evaluate, zip(nii_gt_fullpath, nii_pred_fullpath)) 102 | # now write to output file 103 | with open(join(folder_pred, 'results.csv'), 'w') as f: 104 | f.write("name,DC_CSF,DC_GM,DC_WM,HD95_CSF,HD95_GM,HD95_WM\n") 105 | for fname, r in zip(nii_pred, results): 106 | f.write(fname) 107 | f.write(",%0.4f,%0.4f,%0.4f,%3.3f,%3.3f,%3.3f\n" % r) 108 | 109 | 110 | def main(): 111 | folder_pred = '/data2/huangjunjia/nnFormer/nnFormer_trained_models/nnFormer/3d_fullres/Task666_IBSR/Paper/infers/IBSR_Jig_Final' 112 | evaluate_BraTS_folder(folder_pred, 113 | '/data2/huangjunjia/nnFormer/nnFormer_raw/nnFormer_raw_data/Task666_IBSR/labelsTs/') 114 | 115 | result = pd.read_csv(join(folder_pred, 'results.csv'))[ 116 | ['DC_CSF', 'DC_GM', 'DC_WM', 'HD95_CSF', 'HD95_GM', 'HD95_WM']] 117 | print(result.mean(axis=0)) 118 | 119 | 120 | if __name__ == '__main__': 121 | main() 122 | -------------------------------------------------------------------------------- /ASA_Segmentation/BraTS_dice/inference_WMH.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import SimpleITK as sitk 4 | import numpy as np 5 | from medpy.metric import dc, hd95 6 | from multiprocessing.pool import Pool 7 | from batchgenerators.utilities.file_and_folder_operations import * 8 | import pandas as pd 9 | 10 | 11 | def compute_BraTS_dice(ref, pred): 12 | """ 13 | ref and gt are binary integer numpy.ndarray s 14 | :param ref: 15 | :param gt: 16 | :return: 17 | """ 18 | num_ref = np.sum(ref) 19 | num_pred = np.sum(pred) 20 | 21 | if num_ref == 0: 22 | if num_pred == 0: 23 | return 1 24 | else: 25 | return 0 26 | else: 27 | return dc(pred, ref) 28 | 29 | 30 | def compute_BraTS_HD95(ref, pred): 31 | """ 32 | ref and gt are binary integer numpy.ndarray s 33 | spacing is assumed to be (1, 1, 1) 34 | :param ref: 35 | :param pred: 36 | :return: 37 | """ 38 | num_ref = np.sum(ref) 39 | num_pred = np.sum(pred) 40 | 41 | if num_ref == 0: 42 | if num_pred == 0: 43 | return 0 44 | else: 45 | return 373.12866 46 | elif num_pred == 0 and num_ref != 0: 47 | return 373.12866 48 | else: 49 | return hd95(pred, ref, (1, 1, 1)) 50 | 51 | 52 | def evaluate_BraTS_case(arr: np.ndarray, arr_gt: np.ndarray): 53 | """ 54 | attempting to reimplement the brats evaluation scheme 55 | assumes edema=1, non_enh=2, enh=3 56 | :param arr: 57 | :param arr_gt: 58 | :return: 59 | """ 60 | # whole tumor 61 | mask_gt = (arr_gt == 1).astype(int) 62 | mask_pred = (arr == 1).astype(int) 63 | dc_whole = compute_BraTS_dice(mask_gt, mask_pred) 64 | hd95_whole = compute_BraTS_HD95(mask_gt, mask_pred) 65 | del mask_gt, mask_pred 66 | 67 | return dc_whole, hd95_whole 68 | 69 | 70 | def load_evaluate(filename_gt: str, filename_pred: str): 71 | arr_pred = sitk.GetArrayFromImage(sitk.ReadImage(filename_pred)) 72 | arr_gt = sitk.GetArrayFromImage(sitk.ReadImage(filename_gt)) 73 | return evaluate_BraTS_case(arr_pred, arr_gt) 74 | 75 | 76 | def evaluate_BraTS_folder(folder_pred, folder_gt, num_processes: int = 24, strict=False): 77 | nii_pred = subfiles(folder_pred, suffix='.nii.gz', join=False) 78 | if len(nii_pred) == 0: 79 | return 80 | nii_gt = subfiles(folder_gt, suffix='.nii.gz', join=False) 81 | assert all([i in nii_gt for i in nii_pred]), 'not all predicted niftis have a reference file!' 82 | if strict: 83 | assert all([i in nii_pred for i in nii_gt]), 'not all gt niftis have a predicted file!' 84 | p = Pool(num_processes) 85 | nii_pred_fullpath = [join(folder_pred, i) for i in nii_pred] 86 | nii_gt_fullpath = [join(folder_gt, i) for i in nii_pred] 87 | results = p.starmap(load_evaluate, zip(nii_gt_fullpath, nii_pred_fullpath)) 88 | # now write to output file 89 | with open(join(folder_pred, 'results.csv'), 'w') as f: 90 | f.write("name,DC_WMH,HD95_WMH\n") 91 | for fname, r in zip(nii_pred, results): 92 | f.write(fname) 93 | f.write(",%0.4f,%3.3f\n" % r) 94 | 95 | 96 | def main(): 97 | folder_pred = '/data2/huangjunjia/nnFormer/nnFormer_trained_models/nnFormer/3d_fullres/Task555_WMH/Paper/infers/TransBTS/' 98 | evaluate_BraTS_folder(folder_pred, 99 | '/data2/huangjunjia/nnFormer/nnFormer_raw/nnFormer_raw_data/Task555_WMH/labelsTs/') 100 | 101 | result = pd.read_csv(join(folder_pred, 'results.csv'))[ 102 | ['DC_WMH', 'HD95_WMH']] 103 | print(result.mean(axis=0)) 104 | 105 | 106 | if __name__ == '__main__': 107 | main() 108 | -------------------------------------------------------------------------------- /ASA_Segmentation/Synapse_dice_and_hd/inference.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import SimpleITK as sitk 4 | import numpy as np 5 | def read_nii(path): 6 | return sitk.GetArrayFromImage(sitk.ReadImage(path)) 7 | 8 | def dice(pred, label): 9 | if (pred.sum() + label.sum()) == 0: 10 | return 1 11 | else: 12 | return 2. * np.logical_and(pred, label).sum() / (pred.sum() + label.sum()) 13 | 14 | def process_label(label): 15 | spleen = label == 1 16 | right_kidney = label == 2 17 | left_kidney = label == 3 18 | gallbladder = label == 4 19 | esophagus = label == 5 20 | liver = label == 6 21 | stomach = label == 7 22 | aorta = label == 8 23 | inferior_vena_cava = label == 9 24 | portal_vein_splenic_vein = label == 10 25 | pancreas = label == 11 26 | right_adrenal_gland = label == 12 27 | left_adrenal_gland = label == 13 28 | 29 | return spleen,right_kidney,left_kidney,gallbladder,esophagus,liver,stomach,aorta,inferior_vena_cava,portal_vein_splenic_vein,pancreas,right_adrenal_gland,left_adrenal_gland 30 | 31 | def test(fold): 32 | path='../DATASET/nnFormer_raw/nnFormer_raw_data/Task002_Synapse/' 33 | label_list=sorted(glob.glob(os.path.join(path,'labelsTs','*nii.gz'))) 34 | infer_list=sorted(glob.glob(os.path.join(path,'inferTs',fold,'*nii.gz'))) 35 | print("loading success...") 36 | 37 | Dice_spleen=[] 38 | Dice_right_kidney=[] 39 | Dice_left_kidney=[] 40 | Dice_gallbladder=[] 41 | Dice_esophagus=[] 42 | Dice_liver=[] 43 | Dice_stomach=[] 44 | Dice_aorta=[] 45 | Dice_inferior_vena_cava=[] 46 | Dice_portal_vein_splenic_vein=[] 47 | Dice_pancreas=[] 48 | Dice_right_adrenal_gland=[] 49 | Dice_left_adrenal_gland=[] 50 | 51 | file=path + 'inferTs/'+fold 52 | if not os.path.exists(file): 53 | os.makedirs(file) 54 | fw = open(file+'/8dice_pre.txt', 'a') 55 | 56 | for label_path,infer_path in zip(label_list,infer_list): 57 | print(label_path.split('/')[-1]) 58 | print(infer_path.split('/')[-1]) 59 | label,infer = read_nii(label_path),read_nii(infer_path) 60 | label_spleen,label_right_kidney,label_left_kidney,label_gallbladder,label_esophagus,label_liver,label_stomach,label_aorta,label_inferior_vena_cava,label_portal_vein_splenic_vein,label_pancreas,label_right_adrenal_gland,label_left_adrenal_gland=process_label(label) 61 | 62 | 63 | infer_spleen,infer_right_kidney,infer_left_kidney,infer_gallbladder,infer_esophagus,infer_liver,infer_stomach,infer_aorta,infer_inferior_vena_cava,infer_portal_vein_splenic_vein,infer_pancreas,infer_right_adrenal_gland,infer_left_adrenal_gland=process_label(infer) 64 | 65 | Dice_spleen.append(dice(infer_spleen,label_spleen)) 66 | Dice_right_kidney.append(dice(infer_right_kidney,label_right_kidney)) 67 | Dice_left_kidney.append(dice(infer_left_kidney,label_left_kidney)) 68 | Dice_gallbladder.append(dice(infer_gallbladder,label_gallbladder)) 69 | Dice_esophagus.append(dice(infer_esophagus,label_esophagus)) 70 | Dice_liver.append(dice(infer_liver,label_liver)) 71 | Dice_stomach.append(dice(infer_stomach,label_stomach)) 72 | Dice_aorta.append(dice(infer_aorta,label_aorta)) 73 | Dice_inferior_vena_cava.append(dice(infer_inferior_vena_cava,label_inferior_vena_cava)) 74 | Dice_portal_vein_splenic_vein.append(dice(infer_portal_vein_splenic_vein,label_portal_vein_splenic_vein)) 75 | Dice_pancreas.append(dice(infer_pancreas,label_pancreas)) 76 | Dice_right_adrenal_gland.append(dice(infer_right_adrenal_gland,label_right_adrenal_gland)) 77 | Dice_left_adrenal_gland.append(dice(infer_left_adrenal_gland,label_left_adrenal_gland)) 78 | 79 | fw.write('*'*20+'\n',) 80 | fw.write(infer_path.split('/')[-1]+'\n') 81 | fw.write('Dice_spleen: {:.4f}\n'.format(Dice_spleen[-1])) 82 | fw.write('Dice_right_kidney: {:.4f}\n'.format(Dice_right_kidney[-1])) 83 | fw.write('Dice_left_kidney: {:.4f}\n'.format(Dice_left_kidney[-1])) 84 | fw.write('Dice_gallbladder: {:.4f}\n'.format(Dice_gallbladder[-1])) 85 | fw.write('Dice_esophagus: {:.4f}\n'.format(Dice_esophagus[-1])) 86 | fw.write('Dice_liver: {:.4f}\n'.format(Dice_liver[-1])) 87 | fw.write('Dice_stomach: {:.4f}\n'.format(Dice_stomach[-1])) 88 | fw.write('Dice_aorta: {:.4f}\n'.format(Dice_aorta[-1])) 89 | fw.write('Dice_inferior_vena_cava: {:.4f}\n'.format(Dice_inferior_vena_cava[-1])) 90 | fw.write('Dice_portal_vein_splenic_vein: {:.4f}\n'.format(Dice_portal_vein_splenic_vein[-1])) 91 | fw.write('Dice_pancreas: {:.4f}\n'.format(Dice_pancreas[-1])) 92 | fw.write('Dice_right_adrenal_gland: {:.4f}\n'.format(Dice_right_adrenal_gland[-1])) 93 | fw.write('Dice_left_adrenal_gland: {:.4f}\n'.format(Dice_left_adrenal_gland[-1])) 94 | fw.write('*'*20+'\n') 95 | 96 | fw.write('*'*20+'\n') 97 | fw.write('Mean_Dice\n') 98 | fw.write('Dice_spleen'+str(np.mean(Dice_spleen))+'\n') 99 | fw.write('Dice_right_kidney'+str(np.mean(Dice_right_kidney))+'\n') 100 | fw.write('Dice_left_kidney'+str(np.mean(Dice_left_kidney))+'\n') 101 | fw.write('Dice_gallbladder'+str(np.mean(Dice_gallbladder))+'\n') 102 | fw.write('Dice_esophagus'+str(np.mean(Dice_esophagus))+'\n') 103 | fw.write('Dice_liver'+str(np.mean(Dice_liver))+'\n') 104 | fw.write('Dice_stomach'+str(np.mean(Dice_stomach))+'\n') 105 | fw.write('Dice_aorta'+str(np.mean(Dice_aorta))+'\n') 106 | fw.write('Dice_inferior_vena_cava'+str(np.mean(Dice_inferior_vena_cava))+'\n') 107 | fw.write('Dice_portal_vein_splenic_vein'+str(np.mean(Dice_portal_vein_splenic_vein))+'\n') 108 | fw.write('Dice_pancreas'+str(np.mean(Dice_pancreas))+'\n') 109 | fw.write('Dice_right_adrenal_gland'+str(np.mean(Dice_right_adrenal_gland))+'\n') 110 | fw.write('Dice_left_adrenal_gland'+str(np.mean(Dice_left_adrenal_gland))+'\n') 111 | fw.write('*'*20+'\n') 112 | 113 | dsc=[] 114 | dsc.append(np.mean(Dice_spleen)) 115 | dsc.append(np.mean(Dice_right_kidney)) 116 | dsc.append(np.mean(Dice_left_kidney)) 117 | dsc.append(np.mean(Dice_gallbladder)) 118 | #dsc.append(np.mean(Dice_esophagus)) 119 | dsc.append(np.mean(Dice_liver)) 120 | dsc.append(np.mean(Dice_stomach)) 121 | dsc.append(np.mean(Dice_aorta)) 122 | #dsc.append(np.mean(Dice_inferior_vena_cava)) 123 | #dsc.append(np.mean(Dice_portal_vein_splenic_vein)) 124 | dsc.append(np.mean(Dice_pancreas)) 125 | #dsc.append(np.mean(Dice_right_adrenal_gland)) 126 | #dsc.append(np.mean(Dice_left_adrenal_gland)) 127 | fw.write('DSC:'+str(np.mean(dsc))+'\n') 128 | print('done') 129 | 130 | if __name__ == '__main__': 131 | fold='output' 132 | test(fold) 133 | -------------------------------------------------------------------------------- /ASA_Segmentation/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * 3 | -------------------------------------------------------------------------------- /ASA_Segmentation/configuration.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | default_num_threads = 8 if 'nnFormer_def_n_proc' not in os.environ else int(os.environ['nnFormer_def_n_proc']) 4 | RESAMPLING_SEPARATE_Z_ANISO_THRESHOLD = 3 # determines what threshold to use for resampling the low resolution axis 5 | # separately (with NN) -------------------------------------------------------------------------------- /ASA_Segmentation/dataset_conversion/Task777_MAE.py: -------------------------------------------------------------------------------- 1 | import shutil 2 | from collections import OrderedDict 3 | from copy import deepcopy 4 | from multiprocessing.pool import Pool 5 | from typing import Tuple 6 | 7 | import SimpleITK as sitk 8 | import numpy as np 9 | import scipy.stats as ss 10 | from batchgenerators.utilities.file_and_folder_operations import * 11 | from medpy.metric import dc, hd95 12 | from nnformer.evaluation.region_based_evaluation import get_brats_regions, evaluate_regions 13 | from nnformer.paths import nnFormer_raw_data 14 | from nnformer.postprocessing.consolidate_postprocessing import collect_cv_niftis 15 | 16 | if __name__ == '__main__': 17 | task_name = "Task777_MAE" 18 | root = "/data2/huangjunjia/nnFormer/nnFormer_raw/nnFormer_raw_data/Task777_MAE/labelsTr/" 19 | 20 | target_base = join(nnFormer_raw_data, task_name) 21 | 22 | patient_names = listdir(root) 23 | # for sub in listdir(root): 24 | 25 | json_dict = OrderedDict() 26 | json_dict['name'] = "MAE" 27 | json_dict['description'] = "nothing" 28 | json_dict['tensorImageSize'] = "1D" 29 | json_dict['reference'] = "see ADNI" 30 | json_dict['licence'] = "see ADNI license" 31 | json_dict['release'] = "0.0" 32 | json_dict['modality'] = { 33 | "0": "T1", 34 | } 35 | json_dict['labels'] = { 36 | "0": "background", 37 | "1": "forwground" 38 | } 39 | json_dict['numTraining'] = len(patient_names) 40 | json_dict['numTest'] = 0 41 | json_dict['training'] = [{'image': "./imagesTr/%s" % i, "label": "./labelsTr/%s" % i} for i in 42 | patient_names] 43 | json_dict['test'] = [] 44 | 45 | save_json(json_dict, join(target_base, "dataset.json")) -------------------------------------------------------------------------------- /ASA_Segmentation/dataset_conversion/Task999_BraTS_2021.py: -------------------------------------------------------------------------------- 1 | from copy import deepcopy 2 | from multiprocessing.pool import Pool 3 | 4 | import numpy as np 5 | from collections import OrderedDict 6 | 7 | from batchgenerators.utilities.file_and_folder_operations import * 8 | 9 | import scipy.stats as ss 10 | 11 | from nnformer.dataset_conversion.Task032_BraTS_2018 import convert_labels_back_to_BraTS_2018_2019_convention 12 | from nnformer.dataset_conversion.Task043_BraTS_2019 import copy_BraTS_segmentation_and_convert_labels 13 | from nnformer.evaluation.region_based_evaluation import get_brats_regions, evaluate_regions 14 | from nnformer.paths import nnFormer_raw_data 15 | import SimpleITK as sitk 16 | import shutil 17 | from medpy.metric import dc, hd95 18 | 19 | from nnformer.postprocessing.consolidate_postprocessing import collect_cv_niftis 20 | from typing import Tuple 21 | import random 22 | random.seed(0) 23 | 24 | if __name__ == '__main__': 25 | task_name = "Task999_BraTS2021" 26 | downloaded_data_dir = "/data2/public_data/BraTS2021" 27 | 28 | target_base = join(nnFormer_raw_data, task_name) 29 | target_imagesTr = join(target_base, "imagesTr") 30 | target_labelsTr = join(target_base, "labelsTr") 31 | target_imagesTs = join(target_base, "imagesTs") 32 | target_labelsTs = join(target_base, "labelsTs") 33 | 34 | maybe_mkdir_p(target_imagesTr) 35 | maybe_mkdir_p(target_labelsTr) 36 | maybe_mkdir_p(target_imagesTs) 37 | maybe_mkdir_p(target_labelsTs) 38 | 39 | img_list = [] 40 | patient_names = [] 41 | cur = join(downloaded_data_dir, "imagesTr") 42 | lar = join(downloaded_data_dir, "labelsTr") 43 | for p in os.listdir(cur): 44 | if p[:-12] not in img_list: 45 | img_list.append(p[:-12]) 46 | 47 | # split 48 | total_cnt = len(img_list) 49 | # test_num = int(total_cnt*0.2) 50 | train_num = int(total_cnt*0.8) 51 | random.shuffle(img_list) 52 | 53 | train_list = img_list[:train_num] 54 | test_list = img_list[train_num:] 55 | 56 | 57 | for p in train_list: 58 | patdir = join(cur) 59 | labledir = join(lar) 60 | t1 = join(patdir, p + "_0000.nii.gz") 61 | t1c = join(patdir, p + "_0001.nii.gz") 62 | t2 = join(patdir, p + "_0002.nii.gz") 63 | flair = join(patdir, p + "_0003.nii.gz") 64 | seg = join(labledir, p + ".nii.gz") 65 | assert all([ 66 | isfile(t1), 67 | isfile(t1c), 68 | isfile(t2), 69 | isfile(flair), 70 | isfile(seg) 71 | ]), "!!Error!!" 72 | 73 | shutil.copy(t1, join(target_imagesTr, p + "_0000.nii.gz")) 74 | shutil.copy(t1c, join(target_imagesTr, p + "_0001.nii.gz")) 75 | shutil.copy(t2, join(target_imagesTr, p + "_0002.nii.gz")) 76 | shutil.copy(flair, join(target_imagesTr, p + "_0003.nii.gz")) 77 | shutil.copy(seg, join(target_labelsTr, p+".nii.gz")) 78 | 79 | for p in test_list: 80 | patdir = join(cur) 81 | labledir = join(lar) 82 | t1 = join(patdir, p + "_0000.nii.gz") 83 | t1c = join(patdir, p + "_0001.nii.gz") 84 | t2 = join(patdir, p + "_0002.nii.gz") 85 | flair = join(patdir, p + "_0003.nii.gz") 86 | seg = join(labledir, p + ".nii.gz") 87 | assert all([ 88 | isfile(t1), 89 | isfile(t1c), 90 | isfile(t2), 91 | isfile(flair), 92 | isfile(seg) 93 | ]), "!!Error!!" 94 | 95 | shutil.copy(t1, join(target_imagesTs, p + "_0000.nii.gz")) 96 | shutil.copy(t1c, join(target_imagesTs, p + "_0001.nii.gz")) 97 | shutil.copy(t2, join(target_imagesTs, p + "_0002.nii.gz")) 98 | shutil.copy(flair, join(target_imagesTs, p + "_0003.nii.gz")) 99 | shutil.copy(seg, join(target_labelsTs, p+".nii.gz")) 100 | 101 | 102 | json_dict = OrderedDict() 103 | json_dict['name'] = "BraTS2021" 104 | json_dict['description'] = "nothing" 105 | json_dict['tensorImageSize'] = "4D" 106 | json_dict['reference'] = "see BraTS2020" 107 | json_dict['licence'] = "see BraTS2020 license" 108 | json_dict['release'] = "0.0" 109 | json_dict['modality'] = { 110 | "0": "T1", 111 | "1": "T1ce", 112 | "2": "T2", 113 | "3": "FLAIR" 114 | } 115 | json_dict['labels'] = { 116 | "0": "background", 117 | "1": "edema", 118 | "2": "non-enhancing", 119 | "3": "enhancing", 120 | } 121 | json_dict['numTraining'] = len(train_list) 122 | json_dict['numTest'] = len(test_list) 123 | json_dict['training'] = [{'image': "./imagesTr/%s.nii.gz" % i, "label": "./labelsTr/%s.nii.gz" % i} for i in 124 | train_list] 125 | json_dict['test'] = [] 126 | save_json(json_dict, join(target_base, "dataset.json")) 127 | 128 | print(total_cnt) 129 | print(len(train_list)) 130 | print(len(test_list)) -------------------------------------------------------------------------------- /ASA_Segmentation/dataset_conversion/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/dataset_conversion/utils.py: -------------------------------------------------------------------------------- 1 | 2 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 3 | # 4 | # Licensed under the Apache License, Version 2.0 (the "License"); 5 | # you may not use this file except in compliance with the License. 6 | # You may obtain a copy of the License at 7 | # 8 | # http://www.apache.org/licenses/LICENSE-2.0 9 | # 10 | # Unless required by applicable law or agreed to in writing, software 11 | # distributed under the License is distributed on an "AS IS" BASIS, 12 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | # See the License for the specific language governing permissions and 14 | # limitations under the License. 15 | 16 | 17 | from typing import Tuple 18 | import numpy as np 19 | from batchgenerators.utilities.file_and_folder_operations import * 20 | 21 | 22 | def get_identifiers_from_splitted_files(folder: str): 23 | uniques = np.unique([i[:-12] for i in subfiles(folder, suffix='.nii.gz', join=False)]) 24 | return uniques 25 | 26 | 27 | def generate_dataset_json(output_file: str, imagesTr_dir: str, imagesTs_dir: str, modalities: Tuple, 28 | labels: dict, dataset_name: str, license: str = "hands off!", dataset_description: str = "", 29 | dataset_reference="", dataset_release='0.0'): 30 | """ 31 | :param output_file: This needs to be the full path to the dataset.json you intend to write, so 32 | output_file='DATASET_PATH/dataset.json' where the folder DATASET_PATH points to is the one with the 33 | imagesTr and labelsTr subfolders 34 | :param imagesTr_dir: path to the imagesTr folder of that dataset 35 | :param imagesTs_dir: path to the imagesTs folder of that dataset. Can be None 36 | :param modalities: tuple of strings with modality names. must be in the same order as the images (first entry 37 | corresponds to _0000.nii.gz, etc). Example: ('T1', 'T2', 'FLAIR'). 38 | :param labels: dict with int->str (key->value) mapping the label IDs to label names. Note that 0 is always 39 | supposed to be background! Example: {0: 'background', 1: 'edema', 2: 'enhancing tumor'} 40 | :param dataset_name: The name of the dataset. Can be anything you want 41 | :param license: 42 | :param dataset_description: 43 | :param dataset_reference: website of the dataset, if available 44 | :param dataset_release: 45 | :return: 46 | """ 47 | train_identifiers = get_identifiers_from_splitted_files(imagesTr_dir) 48 | 49 | if imagesTs_dir is not None: 50 | test_identifiers = get_identifiers_from_splitted_files(imagesTs_dir) 51 | else: 52 | test_identifiers = [] 53 | 54 | json_dict = {} 55 | json_dict['name'] = dataset_name 56 | json_dict['description'] = dataset_description 57 | json_dict['tensorImageSize'] = "4D" 58 | json_dict['reference'] = dataset_reference 59 | json_dict['licence'] = license 60 | json_dict['release'] = dataset_release 61 | json_dict['modality'] = {str(i): modalities[i] for i in range(len(modalities))} 62 | json_dict['labels'] = {str(i): labels[i] for i in labels.keys()} 63 | 64 | json_dict['numTraining'] = len(train_identifiers) 65 | json_dict['numTest'] = len(test_identifiers) 66 | json_dict['training'] = [ 67 | {'image': "./imagesTr/%s.nii.gz" % i, "label": "./labelsTr/%s.nii.gz" % i} for i 68 | in 69 | train_identifiers] 70 | json_dict['test'] = ["./imagesTs/%s.nii.gz" % i for i in test_identifiers] 71 | 72 | if not output_file.endswith("dataset.json"): 73 | print("WARNING: output file name is not dataset.json! This may be intentional or not. You decide. " 74 | "Proceeding anyways...") 75 | save_json(json_dict, os.path.join(output_file)) 76 | -------------------------------------------------------------------------------- /ASA_Segmentation/dataset_json/Synapse.json: -------------------------------------------------------------------------------- 1 | { 2 | "labels": { 3 | "0": "background", 4 | "1": "spleen", 5 | "10": "portal vein and splenic vein", 6 | "11": "pancreas", 7 | "12": "right adrenal gland", 8 | "13": "left adrenal gland", 9 | "2": "right kidney", 10 | "3": "left kidney", 11 | "4": "gallbladder", 12 | "5": "esophagus", 13 | "6": "liver", 14 | "7": "stomach", 15 | "8": "aorta", 16 | "9": "inferior vena cava" 17 | }, 18 | "licence": "see challenge website", 19 | "modality": { 20 | "0": "CT" 21 | }, 22 | "name": "Synapse", 23 | "numTest": 12, 24 | "numTraining": 30, 25 | "description": "It seems that we use the whole data to train, but we will split the validation set from the training set", 26 | "reference": "see challenge website", 27 | "release": "0.0", 28 | "tensorImageSize": "4D", 29 | "test": [ 30 | "./imagesTs/img0001.nii.gz", 31 | "./imagesTs/img0002.nii.gz", 32 | "./imagesTs/img0003.nii.gz", 33 | "./imagesTs/img0004.nii.gz", 34 | "./imagesTs/img0008.nii.gz", 35 | "./imagesTs/img0022.nii.gz", 36 | "./imagesTs/img0025.nii.gz", 37 | "./imagesTs/img0029.nii.gz", 38 | "./imagesTs/img0032.nii.gz", 39 | "./imagesTs/img0035.nii.gz", 40 | "./imagesTs/img0036.nii.gz", 41 | "./imagesTs/img0038.nii.gz" 42 | ], 43 | "training": [ 44 | { 45 | "image": "./imagesTr/img0001.nii.gz", 46 | "label": "./labelsTr/label0001.nii.gz" 47 | }, 48 | { 49 | "image": "./imagesTr/img0002.nii.gz", 50 | "label": "./labelsTr/label0002.nii.gz" 51 | }, 52 | { 53 | "image": "./imagesTr/img0003.nii.gz", 54 | "label": "./labelsTr/label0003.nii.gz" 55 | }, 56 | { 57 | "image": "./imagesTr/img0004.nii.gz", 58 | "label": "./labelsTr/label0004.nii.gz" 59 | }, 60 | { 61 | "image": "./imagesTr/img0005.nii.gz", 62 | "label": "./labelsTr/label0005.nii.gz" 63 | }, 64 | { 65 | "image": "./imagesTr/img0006.nii.gz", 66 | "label": "./labelsTr/label0006.nii.gz" 67 | }, 68 | { 69 | "image": "./imagesTr/img0007.nii.gz", 70 | "label": "./labelsTr/label0007.nii.gz" 71 | }, 72 | { 73 | "image": "./imagesTr/img0008.nii.gz", 74 | "label": "./labelsTr/label0008.nii.gz" 75 | }, 76 | { 77 | "image": "./imagesTr/img0009.nii.gz", 78 | "label": "./labelsTr/label0009.nii.gz" 79 | }, 80 | { 81 | "image": "./imagesTr/img0010.nii.gz", 82 | "label": "./labelsTr/label0010.nii.gz" 83 | }, 84 | { 85 | "image": "./imagesTr/img0021.nii.gz", 86 | "label": "./labelsTr/label0021.nii.gz" 87 | }, 88 | { 89 | "image": "./imagesTr/img0022.nii.gz", 90 | "label": "./labelsTr/label0022.nii.gz" 91 | }, 92 | { 93 | "image": "./imagesTr/img0023.nii.gz", 94 | "label": "./labelsTr/label0023.nii.gz" 95 | }, 96 | { 97 | "image": "./imagesTr/img0024.nii.gz", 98 | "label": "./labelsTr/label0024.nii.gz" 99 | }, 100 | { 101 | "image": "./imagesTr/img0025.nii.gz", 102 | "label": "./labelsTr/label0025.nii.gz" 103 | }, 104 | { 105 | "image": "./imagesTr/img0026.nii.gz", 106 | "label": "./labelsTr/label0026.nii.gz" 107 | }, 108 | { 109 | "image": "./imagesTr/img0027.nii.gz", 110 | "label": "./labelsTr/label0027.nii.gz" 111 | }, 112 | { 113 | "image": "./imagesTr/img0028.nii.gz", 114 | "label": "./labelsTr/label0028.nii.gz" 115 | }, 116 | { 117 | "image": "./imagesTr/img0029.nii.gz", 118 | "label": "./labelsTr/label0029.nii.gz" 119 | }, 120 | { 121 | "image": "./imagesTr/img0030.nii.gz", 122 | "label": "./labelsTr/label0030.nii.gz" 123 | }, 124 | { 125 | "image": "./imagesTr/img0031.nii.gz", 126 | "label": "./labelsTr/label0031.nii.gz" 127 | }, 128 | { 129 | "image": "./imagesTr/img0032.nii.gz", 130 | "label": "./labelsTr/label0032.nii.gz" 131 | }, 132 | { 133 | "image": "./imagesTr/img0033.nii.gz", 134 | "label": "./labelsTr/label0033.nii.gz" 135 | }, 136 | { 137 | "image": "./imagesTr/img0034.nii.gz", 138 | "label": "./labelsTr/label0034.nii.gz" 139 | }, 140 | { 141 | "image": "./imagesTr/img0035.nii.gz", 142 | "label": "./labelsTr/label0035.nii.gz" 143 | }, 144 | { 145 | "image": "./imagesTr/img0036.nii.gz", 146 | "label": "./labelsTr/label0036.nii.gz" 147 | }, 148 | { 149 | "image": "./imagesTr/img0037.nii.gz", 150 | "label": "./labelsTr/label0037.nii.gz" 151 | }, 152 | { 153 | "image": "./imagesTr/img0038.nii.gz", 154 | "label": "./labelsTr/label0038.nii.gz" 155 | }, 156 | { 157 | "image": "./imagesTr/img0039.nii.gz", 158 | "label": "./labelsTr/label0039.nii.gz" 159 | }, 160 | { 161 | "image": "./imagesTr/img0040.nii.gz", 162 | "label": "./labelsTr/label0040.nii.gz" 163 | } 164 | ] 165 | } 166 | -------------------------------------------------------------------------------- /ASA_Segmentation/evaluation/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/evaluation/add_dummy_task_with_mean_over_all_tasks.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import json 16 | import numpy as np 17 | from batchgenerators.utilities.file_and_folder_operations import subfiles 18 | import os 19 | from collections import OrderedDict 20 | 21 | folder = "/home/fabian/drives/E132-Projekte/Projects/2018_MedicalDecathlon/Leaderboard" 22 | task_descriptors = ['2D final 2', 23 | '2D final, less pool, dc and topK, fold0', 24 | '2D final pseudo3d 7, fold0', 25 | '2D final, less pool, dc and ce, fold0', 26 | '3D stage0 final 2, fold0', 27 | '3D fullres final 2, fold0'] 28 | task_ids_with_no_stage0 = ["Task001_BrainTumour", "Task004_Hippocampus", "Task005_Prostate"] 29 | 30 | mean_scores = OrderedDict() 31 | for t in task_descriptors: 32 | mean_scores[t] = OrderedDict() 33 | 34 | json_files = subfiles(folder, True, None, ".json", True) 35 | json_files = [i for i in json_files if not i.split("/")[-1].startswith(".")] # stupid mac 36 | for j in json_files: 37 | with open(j, 'r') as f: 38 | res = json.load(f) 39 | task = res['task'] 40 | if task != "Task999_ALL": 41 | name = res['name'] 42 | if name in task_descriptors: 43 | if task not in list(mean_scores[name].keys()): 44 | mean_scores[name][task] = res['results']['mean']['mean'] 45 | else: 46 | raise RuntimeError("duplicate task %s for description %s" % (task, name)) 47 | 48 | for t in task_ids_with_no_stage0: 49 | mean_scores["3D stage0 final 2, fold0"][t] = mean_scores["3D fullres final 2, fold0"][t] 50 | 51 | a = set() 52 | for i in mean_scores.keys(): 53 | a = a.union(list(mean_scores[i].keys())) 54 | 55 | for i in mean_scores.keys(): 56 | try: 57 | for t in list(a): 58 | assert t in mean_scores[i].keys(), "did not find task %s for experiment %s" % (t, i) 59 | new_res = OrderedDict() 60 | new_res['name'] = i 61 | new_res['author'] = "Fabian" 62 | new_res['task'] = "Task999_ALL" 63 | new_res['results'] = OrderedDict() 64 | new_res['results']['mean'] = OrderedDict() 65 | new_res['results']['mean']['mean'] = OrderedDict() 66 | tasks = list(mean_scores[i].keys()) 67 | metrics = mean_scores[i][tasks[0]].keys() 68 | for m in metrics: 69 | foreground_values = [mean_scores[i][n][m] for n in tasks] 70 | new_res['results']['mean']["mean"][m] = np.nanmean(foreground_values) 71 | output_fname = i.replace(" ", "_") + "_globalMean.json" 72 | with open(os.path.join(folder, output_fname), 'w') as f: 73 | json.dump(new_res, f) 74 | except AssertionError: 75 | print("could not process experiment %s" % i) 76 | print("did not find task %s for experiment %s" % (t, i)) 77 | 78 | -------------------------------------------------------------------------------- /ASA_Segmentation/evaluation/add_mean_dice_to_json.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import json 16 | import numpy as np 17 | from batchgenerators.utilities.file_and_folder_operations import subfiles 18 | from collections import OrderedDict 19 | 20 | 21 | def foreground_mean(filename): 22 | with open(filename, 'r') as f: 23 | res = json.load(f) 24 | class_ids = np.array([int(i) for i in res['results']['mean'].keys() if (i != 'mean')]) 25 | class_ids = class_ids[class_ids != 0] 26 | class_ids = class_ids[class_ids != -1] 27 | class_ids = class_ids[class_ids != 99] 28 | 29 | tmp = res['results']['mean'].get('99') 30 | if tmp is not None: 31 | _ = res['results']['mean'].pop('99') 32 | 33 | metrics = res['results']['mean']['1'].keys() 34 | res['results']['mean']["mean"] = OrderedDict() 35 | for m in metrics: 36 | foreground_values = [res['results']['mean'][str(i)][m] for i in class_ids] 37 | res['results']['mean']["mean"][m] = np.nanmean(foreground_values) 38 | with open(filename, 'w') as f: 39 | json.dump(res, f, indent=4, sort_keys=True) 40 | 41 | 42 | def run_in_folder(folder): 43 | json_files = subfiles(folder, True, None, ".json", True) 44 | json_files = [i for i in json_files if not i.split("/")[-1].startswith(".") and not i.endswith("_globalMean.json")] # stupid mac 45 | for j in json_files: 46 | foreground_mean(j) 47 | 48 | 49 | if __name__ == "__main__": 50 | folder = "/media/fabian/Results/nnFormerOutput_final/summary_jsons" 51 | run_in_folder(folder) 52 | -------------------------------------------------------------------------------- /ASA_Segmentation/evaluation/collect_results_files.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import os 16 | import shutil 17 | from batchgenerators.utilities.file_and_folder_operations import subdirs, subfiles 18 | 19 | 20 | def crawl_and_copy(current_folder, out_folder, prefix="fabian_", suffix="ummary.json"): 21 | """ 22 | This script will run recursively through all subfolders of current_folder and copy all files that end with 23 | suffix with some automatically generated prefix into out_folder 24 | :param current_folder: 25 | :param out_folder: 26 | :param prefix: 27 | :return: 28 | """ 29 | s = subdirs(current_folder, join=False) 30 | f = subfiles(current_folder, join=False) 31 | f = [i for i in f if i.endswith(suffix)] 32 | if current_folder.find("fold0") != -1: 33 | for fl in f: 34 | shutil.copy(os.path.join(current_folder, fl), os.path.join(out_folder, prefix+fl)) 35 | for su in s: 36 | if prefix == "": 37 | add = su 38 | else: 39 | add = "__" + su 40 | crawl_and_copy(os.path.join(current_folder, su), out_folder, prefix=prefix+add) 41 | 42 | 43 | if __name__ == "__main__": 44 | from nnformer.paths import network_training_output_dir 45 | output_folder = "/home/fabian/PhD/results/nnFormerV2/leaderboard" 46 | crawl_and_copy(network_training_output_dir, output_folder) 47 | from nnformer.evaluation.add_mean_dice_to_json import run_in_folder 48 | run_in_folder(output_folder) 49 | -------------------------------------------------------------------------------- /ASA_Segmentation/evaluation/model_selection/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/evaluation/model_selection/collect_all_fold0_results_and_summarize_in_one_csv.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from nnformer.evaluation.model_selection.summarize_results_in_one_json import summarize2 16 | from nnformer.paths import network_training_output_dir 17 | from batchgenerators.utilities.file_and_folder_operations import * 18 | 19 | if __name__ == "__main__": 20 | summary_output_folder = join(network_training_output_dir, "summary_jsons_fold0_new") 21 | maybe_mkdir_p(summary_output_folder) 22 | summarize2(['all'], output_dir=summary_output_folder, folds=(0,)) 23 | 24 | results_csv = join(network_training_output_dir, "summary_fold0.csv") 25 | 26 | summary_files = subfiles(summary_output_folder, suffix='.json', join=False) 27 | 28 | with open(results_csv, 'w') as f: 29 | for s in summary_files: 30 | if s.find("ensemble") == -1: 31 | task, network, trainer, plans, validation_folder, folds = s.split("__") 32 | else: 33 | n1, n2 = s.split("--") 34 | n1 = n1[n1.find("ensemble_") + len("ensemble_") :] 35 | task = s.split("__")[0] 36 | network = "ensemble" 37 | trainer = n1 38 | plans = n2 39 | validation_folder = "none" 40 | folds = folds[:-len('.json')] 41 | results = load_json(join(summary_output_folder, s)) 42 | results_mean = results['results']['mean']['mean']['Dice'] 43 | results_median = results['results']['median']['mean']['Dice'] 44 | f.write("%s,%s,%s,%s,%s,%02.4f,%02.4f\n" % (task, 45 | network, trainer, validation_folder, plans, results_mean, results_median)) 46 | 47 | summary_output_folder = join(network_training_output_dir, "summary_jsons_new") 48 | maybe_mkdir_p(summary_output_folder) 49 | summarize2(['all'], output_dir=summary_output_folder) 50 | 51 | results_csv = join(network_training_output_dir, "summary_allFolds.csv") 52 | 53 | summary_files = subfiles(summary_output_folder, suffix='.json', join=False) 54 | 55 | with open(results_csv, 'w') as f: 56 | for s in summary_files: 57 | if s.find("ensemble") == -1: 58 | task, network, trainer, plans, validation_folder, folds = s.split("__") 59 | else: 60 | n1, n2 = s.split("--") 61 | n1 = n1[n1.find("ensemble_") + len("ensemble_") :] 62 | task = s.split("__")[0] 63 | network = "ensemble" 64 | trainer = n1 65 | plans = n2 66 | validation_folder = "none" 67 | folds = folds[:-len('.json')] 68 | results = load_json(join(summary_output_folder, s)) 69 | results_mean = results['results']['mean']['mean']['Dice'] 70 | results_median = results['results']['median']['mean']['Dice'] 71 | f.write("%s,%s,%s,%s,%s,%02.4f,%02.4f\n" % (task, 72 | network, trainer, validation_folder, plans, results_mean, results_median)) 73 | 74 | -------------------------------------------------------------------------------- /ASA_Segmentation/evaluation/model_selection/summarize_results_with_plans.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from batchgenerators.utilities.file_and_folder_operations import * 17 | import os 18 | from nnformer.evaluation.model_selection.summarize_results_in_one_json import summarize 19 | from nnformer.paths import network_training_output_dir 20 | import numpy as np 21 | 22 | 23 | def list_to_string(l, delim=","): 24 | st = "%03.3f" % l[0] 25 | for i in l[1:]: 26 | st += delim + "%03.3f" % i 27 | return st 28 | 29 | 30 | def write_plans_to_file(f, plans_file, stage=0, do_linebreak_at_end=True, override_name=None): 31 | a = load_pickle(plans_file) 32 | stages = list(a['plans_per_stage'].keys()) 33 | stages.sort() 34 | patch_size_in_mm = [i * j for i, j in zip(a['plans_per_stage'][stages[stage]]['patch_size'], 35 | a['plans_per_stage'][stages[stage]]['current_spacing'])] 36 | median_patient_size_in_mm = [i * j for i, j in zip(a['plans_per_stage'][stages[stage]]['median_patient_size_in_voxels'], 37 | a['plans_per_stage'][stages[stage]]['current_spacing'])] 38 | if override_name is None: 39 | f.write(plans_file.split("/")[-2] + "__" + plans_file.split("/")[-1]) 40 | else: 41 | f.write(override_name) 42 | f.write(";%d" % stage) 43 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['batch_size'])) 44 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['num_pool_per_axis'])) 45 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['patch_size'])) 46 | f.write(";%s" % list_to_string(patch_size_in_mm)) 47 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['median_patient_size_in_voxels'])) 48 | f.write(";%s" % list_to_string(median_patient_size_in_mm)) 49 | f.write(";%s" % list_to_string(a['plans_per_stage'][stages[stage]]['current_spacing'])) 50 | f.write(";%s" % list_to_string(a['plans_per_stage'][stages[stage]]['original_spacing'])) 51 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['pool_op_kernel_sizes'])) 52 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['conv_kernel_sizes'])) 53 | if do_linebreak_at_end: 54 | f.write("\n") 55 | 56 | 57 | if __name__ == "__main__": 58 | summarize((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 24, 27), output_dir=join(network_training_output_dir, "summary_fold0"), folds=(0,)) 59 | base_dir = os.environ['RESULTS_FOLDER'] 60 | nnformers = ['nnFormerV2', 'nnFormerV2_zspacing'] 61 | task_ids = list(range(99)) 62 | with open("summary.csv", 'w') as f: 63 | f.write("identifier;stage;batch_size;num_pool_per_axis;patch_size;patch_size(mm);median_patient_size_in_voxels;median_patient_size_in_mm;current_spacing;original_spacing;pool_op_kernel_sizes;conv_kernel_sizes;patient_dc;global_dc\n") 64 | for i in task_ids: 65 | for nnformer in nnformers: 66 | try: 67 | summary_folder = join(base_dir, nnformer, "summary_fold0") 68 | if isdir(summary_folder): 69 | summary_files = subfiles(summary_folder, join=False, prefix="Task%03.0d_" % i, suffix=".json", sort=True) 70 | for s in summary_files: 71 | tmp = s.split("__") 72 | trainer = tmp[2] 73 | 74 | expected_output_folder = join(base_dir, nnformer, tmp[1], tmp[0], tmp[2].split(".")[0]) 75 | name = tmp[0] + "__" + nnformer + "__" + tmp[1] + "__" + tmp[2].split(".")[0] 76 | global_dice_json = join(base_dir, nnformer, tmp[1], tmp[0], tmp[2].split(".")[0], "fold_0", "validation_tiledTrue_doMirror_True", "global_dice.json") 77 | 78 | if not isdir(expected_output_folder) or len(tmp) > 3: 79 | if len(tmp) == 2: 80 | continue 81 | expected_output_folder = join(base_dir, nnformer, tmp[1], tmp[0], tmp[2] + "__" + tmp[3].split(".")[0]) 82 | name = tmp[0] + "__" + nnformer + "__" + tmp[1] + "__" + tmp[2] + "__" + tmp[3].split(".")[0] 83 | global_dice_json = join(base_dir, nnformer, tmp[1], tmp[0], tmp[2] + "__" + tmp[3].split(".")[0], "fold_0", "validation_tiledTrue_doMirror_True", "global_dice.json") 84 | 85 | assert isdir(expected_output_folder), "expected output dir not found" 86 | plans_file = join(expected_output_folder, "plans.pkl") 87 | assert isfile(plans_file) 88 | 89 | plans = load_pickle(plans_file) 90 | num_stages = len(plans['plans_per_stage']) 91 | if num_stages > 1 and tmp[1] == "3d_fullres": 92 | stage = 1 93 | elif (num_stages == 1 and tmp[1] == "3d_fullres") or tmp[1] == "3d_lowres": 94 | stage = 0 95 | else: 96 | print("skipping", s) 97 | continue 98 | 99 | g_dc = load_json(global_dice_json) 100 | mn_glob_dc = np.mean(list(g_dc.values())) 101 | 102 | write_plans_to_file(f, plans_file, stage, False, name) 103 | # now read and add result to end of line 104 | results = load_json(join(summary_folder, s)) 105 | mean_dc = results['results']['mean']['mean']['Dice'] 106 | f.write(";%03.3f" % mean_dc) 107 | f.write(";%03.3f\n" % mn_glob_dc) 108 | print(name, mean_dc) 109 | except Exception as e: 110 | print(e) 111 | -------------------------------------------------------------------------------- /ASA_Segmentation/evaluation/region_based_evaluation.py: -------------------------------------------------------------------------------- 1 | from copy import deepcopy 2 | from multiprocessing.pool import Pool 3 | 4 | from batchgenerators.utilities.file_and_folder_operations import * 5 | from medpy import metric 6 | import SimpleITK as sitk 7 | import numpy as np 8 | from nnformer.configuration import default_num_threads 9 | from nnformer.postprocessing.consolidate_postprocessing import collect_cv_niftis 10 | 11 | 12 | def get_brats_regions(): 13 | """ 14 | this is only valid for the brats data in here where the labels are 1, 2, and 3. The original brats data have a 15 | different labeling convention! 16 | :return: 17 | """ 18 | regions = { 19 | "whole tumor": (1, 2, 3), 20 | "tumor core": (2, 3), 21 | "enhancing tumor": (3,) 22 | } 23 | return regions 24 | 25 | 26 | def get_KiTS_regions(): 27 | regions = { 28 | "kidney incl tumor": (1, 2), 29 | "tumor": (2,) 30 | } 31 | return regions 32 | 33 | 34 | def create_region_from_mask(mask, join_labels: tuple): 35 | mask_new = np.zeros_like(mask, dtype=np.uint8) 36 | for l in join_labels: 37 | mask_new[mask == l] = 1 38 | return mask_new 39 | 40 | 41 | def evaluate_case(file_pred: str, file_gt: str, regions): 42 | image_gt = sitk.GetArrayFromImage(sitk.ReadImage(file_gt)) 43 | image_pred = sitk.GetArrayFromImage(sitk.ReadImage(file_pred)) 44 | results = [] 45 | for r in regions: 46 | mask_pred = create_region_from_mask(image_pred, r) 47 | mask_gt = create_region_from_mask(image_gt, r) 48 | dc = np.nan if np.sum(mask_gt) == 0 and np.sum(mask_pred) == 0 else metric.dc(mask_pred, mask_gt) 49 | results.append(dc) 50 | return results 51 | 52 | 53 | def evaluate_regions(folder_predicted: str, folder_gt: str, regions: dict, processes=default_num_threads): 54 | region_names = list(regions.keys()) 55 | files_in_pred = subfiles(folder_predicted, suffix='.nii.gz', join=False) 56 | files_in_gt = subfiles(folder_gt, suffix='.nii.gz', join=False) 57 | have_no_gt = [i for i in files_in_pred if i not in files_in_gt] 58 | assert len(have_no_gt) == 0, "Some files in folder_predicted have not ground truth in folder_gt" 59 | have_no_pred = [i for i in files_in_gt if i not in files_in_pred] 60 | if len(have_no_pred) > 0: 61 | print("WARNING! Some files in folder_gt were not predicted (not present in folder_predicted)!") 62 | 63 | files_in_gt.sort() 64 | files_in_pred.sort() 65 | 66 | # run for all cases 67 | full_filenames_gt = [join(folder_gt, i) for i in files_in_pred] 68 | full_filenames_pred = [join(folder_predicted, i) for i in files_in_pred] 69 | 70 | p = Pool(processes) 71 | res = p.starmap(evaluate_case, zip(full_filenames_pred, full_filenames_gt, [list(regions.values())] * len(files_in_gt))) 72 | p.close() 73 | p.join() 74 | 75 | all_results = {r: [] for r in region_names} 76 | with open(join(folder_predicted, 'summary.csv'), 'w') as f: 77 | f.write("casename") 78 | for r in region_names: 79 | f.write(",%s" % r) 80 | f.write("\n") 81 | for i in range(len(files_in_pred)): 82 | f.write(files_in_pred[i][:-7]) 83 | result_here = res[i] 84 | for k, r in enumerate(region_names): 85 | dc = result_here[k] 86 | f.write(",%02.4f" % dc) 87 | all_results[r].append(dc) 88 | f.write("\n") 89 | 90 | f.write('mean') 91 | for r in region_names: 92 | f.write(",%02.4f" % np.nanmean(all_results[r])) 93 | f.write("\n") 94 | f.write('median') 95 | for r in region_names: 96 | f.write(",%02.4f" % np.nanmedian(all_results[r])) 97 | f.write("\n") 98 | 99 | f.write('mean (nan is 1)') 100 | for r in region_names: 101 | tmp = np.array(all_results[r]) 102 | tmp[np.isnan(tmp)] = 1 103 | f.write(",%02.4f" % np.mean(tmp)) 104 | f.write("\n") 105 | f.write('median (nan is 1)') 106 | for r in region_names: 107 | tmp = np.array(all_results[r]) 108 | tmp[np.isnan(tmp)] = 1 109 | f.write(",%02.4f" % np.median(tmp)) 110 | f.write("\n") 111 | 112 | 113 | if __name__ == '__main__': 114 | collect_cv_niftis('./', './cv_niftis') 115 | evaluate_regions('./cv_niftis/', './gt_niftis/', get_brats_regions()) 116 | -------------------------------------------------------------------------------- /ASA_Segmentation/evaluation/surface_dice.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | import numpy as np 17 | from medpy.metric.binary import __surface_distances 18 | 19 | 20 | def normalized_surface_dice(a: np.ndarray, b: np.ndarray, threshold: float, spacing: tuple = None, connectivity=1): 21 | """ 22 | This implementation differs from the official surface dice implementation! These two are not comparable!!!!! 23 | 24 | The normalized surface dice is symmetric, so it should not matter whether a or b is the reference image 25 | 26 | This implementation natively supports 2D and 3D images. Whether other dimensions are supported depends on the 27 | __surface_distances implementation in medpy 28 | 29 | :param a: image 1, must have the same shape as b 30 | :param b: image 2, must have the same shape as a 31 | :param threshold: distances below this threshold will be counted as true positives. Threshold is in mm, not voxels! 32 | (if spacing = (1, 1(, 1)) then one voxel=1mm so the threshold is effectively in voxels) 33 | must be a tuple of len dimension(a) 34 | :param spacing: how many mm is one voxel in reality? Can be left at None, we then assume an isotropic spacing of 1mm 35 | :param connectivity: see scipy.ndimage.generate_binary_structure for more information. I suggest you leave that 36 | one alone 37 | :return: 38 | """ 39 | assert all([i == j for i, j in zip(a.shape, b.shape)]), "a and b must have the same shape. a.shape= %s, " \ 40 | "b.shape= %s" % (str(a.shape), str(b.shape)) 41 | if spacing is None: 42 | spacing = tuple([1 for _ in range(len(a.shape))]) 43 | a_to_b = __surface_distances(a, b, spacing, connectivity) 44 | b_to_a = __surface_distances(b, a, spacing, connectivity) 45 | 46 | numel_a = len(a_to_b) 47 | numel_b = len(b_to_a) 48 | 49 | tp_a = np.sum(a_to_b <= threshold) / numel_a 50 | tp_b = np.sum(b_to_a <= threshold) / numel_b 51 | 52 | fp = np.sum(a_to_b > threshold) / numel_a 53 | fn = np.sum(b_to_a > threshold) / numel_b 54 | 55 | dc = (tp_a + tp_b) / (tp_a + tp_b + fp + fn + 1e-8) # 1e-8 just so that we don't get div by 0 56 | return dc 57 | 58 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/alternative_experiment_planning/experiment_planner_baseline_3DUNet_v21_3convperstage.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from copy import deepcopy 16 | 17 | import numpy as np 18 | from nnformer.experiment_planning.common_utils import get_pool_and_conv_props 19 | from nnformer.experiment_planning.experiment_planner_baseline_3DUNet import ExperimentPlanner 20 | from nnformer.experiment_planning.experiment_planner_baseline_3DUNet_v21 import ExperimentPlanner3D_v21 21 | from nnformer.network_architecture.generic_UNet import Generic_UNet 22 | from nnformer.paths import * 23 | 24 | 25 | class ExperimentPlanner3D_v21_3cps(ExperimentPlanner3D_v21): 26 | """ 27 | have 3x conv-in-lrelu per resolution instead of 2 while remaining in the same memory budget 28 | 29 | This only works with 3d fullres because we use the same data as ExperimentPlanner3D_v21. Lowres would require to 30 | rerun preprocesing (different patch size = different 3d lowres target spacing) 31 | """ 32 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 33 | super(ExperimentPlanner3D_v21_3cps, self).__init__(folder_with_cropped_data, preprocessed_output_folder) 34 | self.plans_fname = join(self.preprocessed_output_folder, 35 | "nnFormerPlansv2.1_3cps_plans_3D.pkl") 36 | self.unet_base_num_features = 32 37 | self.conv_per_stage = 3 38 | 39 | def run_preprocessing(self, num_threads): 40 | pass 41 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/alternative_experiment_planning/experiment_planner_baseline_3DUNet_v22.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | from nnformer.experiment_planning.experiment_planner_baseline_3DUNet_v21 import \ 17 | ExperimentPlanner3D_v21 18 | from nnformer.paths import * 19 | 20 | 21 | class ExperimentPlanner3D_v22(ExperimentPlanner3D_v21): 22 | """ 23 | """ 24 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 25 | super().__init__(folder_with_cropped_data, preprocessed_output_folder) 26 | self.data_identifier = "nnFormerData_plans_v2.2" 27 | self.plans_fname = join(self.preprocessed_output_folder, 28 | "nnFormerPlansv2.2_plans_3D.pkl") 29 | 30 | def get_target_spacing(self): 31 | spacings = self.dataset_properties['all_spacings'] 32 | sizes = self.dataset_properties['all_sizes'] 33 | 34 | target = np.percentile(np.vstack(spacings), self.target_spacing_percentile, 0) 35 | target_size = np.percentile(np.vstack(sizes), self.target_spacing_percentile, 0) 36 | target_size_mm = np.array(target) * np.array(target_size) 37 | # we need to identify datasets for which a different target spacing could be beneficial. These datasets have 38 | # the following properties: 39 | # - one axis which much lower resolution than the others 40 | # - the lowres axis has much less voxels than the others 41 | # - (the size in mm of the lowres axis is also reduced) 42 | worst_spacing_axis = np.argmax(target) 43 | other_axes = [i for i in range(len(target)) if i != worst_spacing_axis] 44 | other_spacings = [target[i] for i in other_axes] 45 | other_sizes = [target_size[i] for i in other_axes] 46 | 47 | has_aniso_spacing = target[worst_spacing_axis] > (self.anisotropy_threshold * max(other_spacings)) 48 | has_aniso_voxels = target_size[worst_spacing_axis] * self.anisotropy_threshold < min(other_sizes) 49 | # we don't use the last one for now 50 | #median_size_in_mm = target[target_size_mm] * RESAMPLING_SEPARATE_Z_ANISOTROPY_THRESHOLD < max(target_size_mm) 51 | 52 | if has_aniso_spacing and has_aniso_voxels: 53 | spacings_of_that_axis = np.vstack(spacings)[:, worst_spacing_axis] 54 | target_spacing_of_that_axis = np.percentile(spacings_of_that_axis, 10) 55 | # don't let the spacing of that axis get higher than self.anisotropy_thresholdxthe_other_axes 56 | target_spacing_of_that_axis = max(max(other_spacings) * self.anisotropy_threshold, target_spacing_of_that_axis) 57 | target[worst_spacing_axis] = target_spacing_of_that_axis 58 | return target 59 | 60 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/alternative_experiment_planning/experiment_planner_baseline_3DUNet_v23.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from nnformer.experiment_planning.experiment_planner_baseline_3DUNet_v21 import \ 16 | ExperimentPlanner3D_v21 17 | from nnformer.paths import * 18 | 19 | 20 | class ExperimentPlanner3D_v23(ExperimentPlanner3D_v21): 21 | """ 22 | """ 23 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 24 | super(ExperimentPlanner3D_v23, self).__init__(folder_with_cropped_data, preprocessed_output_folder) 25 | self.data_identifier = "nnFormerData_plans_v2.3" 26 | self.plans_fname = join(self.preprocessed_output_folder, 27 | "nnFormerPlansv2.3_plans_3D.pkl") 28 | self.preprocessor_name = "Preprocessor3DDifferentResampling" 29 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/alternative_experiment_planning/normalization/experiment_planner_2DUNet_v21_RGB_scaleto_0_1.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from nnformer.experiment_planning.experiment_planner_baseline_2DUNet_v21 import ExperimentPlanner2D_v21 17 | from nnformer.paths import * 18 | 19 | 20 | class ExperimentPlanner2D_v21_RGB_scaleTo_0_1(ExperimentPlanner2D_v21): 21 | """ 22 | used by tutorial nnformer.tutorials.custom_preprocessing 23 | """ 24 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 25 | super().__init__(folder_with_cropped_data, preprocessed_output_folder) 26 | self.data_identifier = "nnFormer_RGB_scaleTo_0_1" 27 | self.plans_fname = join(self.preprocessed_output_folder, "nnFormer_RGB_scaleTo_0_1" + "_plans_2D.pkl") 28 | 29 | # The custom preprocessor class we intend to use is GenericPreprocessor_scale_uint8_to_0_1. It must be located 30 | # in nnformer.preprocessing (any file and submodule) and will be found by its name. Make sure to always define 31 | # unique names! 32 | self.preprocessor_name = 'GenericPreprocessor_scale_uint8_to_0_1' 33 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/alternative_experiment_planning/normalization/experiment_planner_3DUNet_CT2.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from collections import OrderedDict 17 | 18 | from nnformer.experiment_planning.experiment_planner_baseline_3DUNet import ExperimentPlanner 19 | from nnformer.paths import * 20 | 21 | 22 | class ExperimentPlannerCT2(ExperimentPlanner): 23 | """ 24 | preprocesses CT data with the "CT2" normalization. 25 | 26 | (clip range comes from training set and is the 0.5 and 99.5 percentile of intensities in foreground) 27 | CT = clip to range, then normalize with global mn and sd (computed on foreground in training set) 28 | CT2 = clip to range, normalize each case separately with its own mn and std (computed within the area that was in clip_range) 29 | """ 30 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 31 | super(ExperimentPlannerCT2, self).__init__(folder_with_cropped_data, preprocessed_output_folder) 32 | self.data_identifier = "nnFormer_CT2" 33 | self.plans_fname = join(self.preprocessed_output_folder, "nnFormerPlans" + "CT2_plans_3D.pkl") 34 | 35 | def determine_normalization_scheme(self): 36 | schemes = OrderedDict() 37 | modalities = self.dataset_properties['modalities'] 38 | num_modalities = len(list(modalities.keys())) 39 | 40 | for i in range(num_modalities): 41 | if modalities[i] == "CT": 42 | schemes[i] = "CT2" 43 | else: 44 | schemes[i] = "nonCT" 45 | return schemes 46 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/alternative_experiment_planning/normalization/experiment_planner_3DUNet_nonCT.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from collections import OrderedDict 17 | 18 | from nnformer.experiment_planning.experiment_planner_baseline_3DUNet import ExperimentPlanner 19 | from nnformer.paths import * 20 | 21 | 22 | class ExperimentPlannernonCT(ExperimentPlanner): 23 | """ 24 | Preprocesses all data in nonCT mode (this is what we use for MRI per default, but here it is applied to CT images 25 | as well) 26 | """ 27 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 28 | super(ExperimentPlannernonCT, self).__init__(folder_with_cropped_data, preprocessed_output_folder) 29 | self.data_identifier = "nnFormer_nonCT" 30 | self.plans_fname = join(self.preprocessed_output_folder, "nnFormerPlans" + "nonCT_plans_3D.pkl") 31 | 32 | def determine_normalization_scheme(self): 33 | schemes = OrderedDict() 34 | modalities = self.dataset_properties['modalities'] 35 | num_modalities = len(list(modalities.keys())) 36 | 37 | for i in range(num_modalities): 38 | if modalities[i] == "CT": 39 | schemes[i] = "nonCT" 40 | else: 41 | schemes[i] = "nonCT" 42 | return schemes 43 | 44 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/alternative_experiment_planning/patch_size/experiment_planner_3DUNet_isotropic_in_voxels.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from copy import deepcopy 17 | 18 | import numpy as np 19 | from nnformer.experiment_planning.common_utils import get_pool_and_conv_props_poolLateV2 20 | from nnformer.experiment_planning.experiment_planner_baseline_3DUNet import ExperimentPlanner 21 | from nnformer.network_architecture.generic_UNet import Generic_UNet 22 | from nnformer.paths import * 23 | 24 | 25 | class ExperimentPlanner3D_IsoPatchesInVoxels(ExperimentPlanner): 26 | """ 27 | patches that are isotropic in the number of voxels (not mm), such as 128x128x128 allow more voxels to be processed 28 | at once because we don't have to do annoying pooling stuff 29 | 30 | CAREFUL! 31 | this one does not support transpose_forward and transpose_backward 32 | """ 33 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 34 | super(ExperimentPlanner3D_IsoPatchesInVoxels, self).__init__(folder_with_cropped_data, preprocessed_output_folder) 35 | self.data_identifier = "nnFormerData_isoPatchesInVoxels" 36 | self.plans_fname = join(self.preprocessed_output_folder, "nnFormerPlans" + "fixedisoPatchesInVoxels_plans_3D.pkl") 37 | 38 | def get_properties_for_stage(self, current_spacing, original_spacing, original_shape, num_cases, 39 | num_modalities, num_classes): 40 | """ 41 | """ 42 | new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) 43 | dataset_num_voxels = np.prod(new_median_shape) * num_cases 44 | 45 | input_patch_size = new_median_shape 46 | 47 | network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ 48 | shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(input_patch_size, 49 | self.unet_featuremap_min_edge_length, 50 | self.unet_max_numpool, 51 | current_spacing) 52 | 53 | ref = Generic_UNet.use_this_for_batch_size_computation_3D 54 | here = Generic_UNet.compute_approx_vram_consumption(new_shp, network_num_pool_per_axis, 55 | self.unet_base_num_features, 56 | self.unet_max_num_filters, num_modalities, 57 | num_classes, 58 | pool_op_kernel_sizes, conv_per_stage=self.conv_per_stage) 59 | while here > ref: 60 | # find the largest axis. If patch is isotropic, pick the axis with the largest spacing 61 | if len(np.unique(new_shp)) == 1: 62 | axis_to_be_reduced = np.argsort(current_spacing)[-1] 63 | else: 64 | axis_to_be_reduced = np.argsort(new_shp)[-1] 65 | 66 | tmp = deepcopy(new_shp) 67 | tmp[axis_to_be_reduced] -= shape_must_be_divisible_by[axis_to_be_reduced] 68 | _, _, _, _, shape_must_be_divisible_by_new = \ 69 | get_pool_and_conv_props_poolLateV2(tmp, 70 | self.unet_featuremap_min_edge_length, 71 | self.unet_max_numpool, 72 | current_spacing) 73 | new_shp[axis_to_be_reduced] -= shape_must_be_divisible_by_new[axis_to_be_reduced] 74 | 75 | # we have to recompute numpool now: 76 | network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ 77 | shape_must_be_divisible_by = get_pool_and_conv_props_poolLateV2(new_shp, 78 | self.unet_featuremap_min_edge_length, 79 | self.unet_max_numpool, 80 | current_spacing) 81 | 82 | here = Generic_UNet.compute_approx_vram_consumption(new_shp, network_num_pool_per_axis, 83 | self.unet_base_num_features, 84 | self.unet_max_num_filters, num_modalities, 85 | num_classes, pool_op_kernel_sizes, 86 | conv_per_stage=self.conv_per_stage) 87 | print(new_shp) 88 | 89 | input_patch_size = new_shp 90 | 91 | batch_size = Generic_UNet.DEFAULT_BATCH_SIZE_3D # This is what works with 128**3 92 | batch_size = int(np.floor(max(ref / here, 1) * batch_size)) 93 | 94 | # check if batch size is too large 95 | max_batch_size = np.round(self.batch_size_covers_max_percent_of_dataset * dataset_num_voxels / 96 | np.prod(input_patch_size, dtype=np.int64)).astype(int) 97 | max_batch_size = max(max_batch_size, self.unet_min_batch_size) 98 | batch_size = max(1, min(batch_size, max_batch_size)) 99 | 100 | do_dummy_2D_data_aug = (max(input_patch_size) / input_patch_size[ 101 | 0]) > self.anisotropy_threshold 102 | 103 | plan = { 104 | 'batch_size': batch_size, 105 | 'num_pool_per_axis': network_num_pool_per_axis, 106 | 'patch_size': input_patch_size, 107 | 'median_patient_size_in_voxels': new_median_shape, 108 | 'current_spacing': current_spacing, 109 | 'original_spacing': original_spacing, 110 | 'do_dummy_2D_data_aug': do_dummy_2D_data_aug, 111 | 'pool_op_kernel_sizes': pool_op_kernel_sizes, 112 | 'conv_kernel_sizes': conv_kernel_sizes, 113 | } 114 | return plan 115 | 116 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/alternative_experiment_planning/target_spacing/experiment_planner_baseline_3DUNet_targetSpacingForAnisoAxis.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | from nnformer.experiment_planning.experiment_planner_baseline_3DUNet import ExperimentPlanner 17 | from nnformer.paths import * 18 | 19 | 20 | class ExperimentPlannerTargetSpacingForAnisoAxis(ExperimentPlanner): 21 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 22 | super().__init__(folder_with_cropped_data, preprocessed_output_folder) 23 | self.data_identifier = "nnFormerData_targetSpacingForAnisoAxis" 24 | self.plans_fname = join(self.preprocessed_output_folder, 25 | "nnFormerPlans" + "targetSpacingForAnisoAxis_plans_3D.pkl") 26 | 27 | def get_target_spacing(self): 28 | """ 29 | per default we use the 50th percentile=median for the target spacing. Higher spacing results in smaller data 30 | and thus faster and easier training. Smaller spacing results in larger data and thus longer and harder training 31 | 32 | For some datasets the median is not a good choice. Those are the datasets where the spacing is very anisotropic 33 | (for example ACDC with (10, 1.5, 1.5)). These datasets still have examples with a pacing of 5 or 6 mm in the low 34 | resolution axis. Choosing the median here will result in bad interpolation artifacts that can substantially 35 | impact performance (due to the low number of slices). 36 | """ 37 | spacings = self.dataset_properties['all_spacings'] 38 | sizes = self.dataset_properties['all_sizes'] 39 | 40 | target = np.percentile(np.vstack(spacings), self.target_spacing_percentile, 0) 41 | target_size = np.percentile(np.vstack(sizes), self.target_spacing_percentile, 0) 42 | target_size_mm = np.array(target) * np.array(target_size) 43 | # we need to identify datasets for which a different target spacing could be beneficial. These datasets have 44 | # the following properties: 45 | # - one axis which much lower resolution than the others 46 | # - the lowres axis has much less voxels than the others 47 | # - (the size in mm of the lowres axis is also reduced) 48 | worst_spacing_axis = np.argmax(target) 49 | other_axes = [i for i in range(len(target)) if i != worst_spacing_axis] 50 | other_spacings = [target[i] for i in other_axes] 51 | other_sizes = [target_size[i] for i in other_axes] 52 | 53 | has_aniso_spacing = target[worst_spacing_axis] > (self.anisotropy_threshold * max(other_spacings)) 54 | has_aniso_voxels = target_size[worst_spacing_axis] * self.anisotropy_threshold < max(other_sizes) 55 | # we don't use the last one for now 56 | #median_size_in_mm = target[target_size_mm] * RESAMPLING_SEPARATE_Z_ANISOTROPY_THRESHOLD < max(target_size_mm) 57 | 58 | if has_aniso_spacing and has_aniso_voxels: 59 | spacings_of_that_axis = np.vstack(spacings)[:, worst_spacing_axis] 60 | target_spacing_of_that_axis = np.percentile(spacings_of_that_axis, 10) 61 | target[worst_spacing_axis] = target_spacing_of_that_axis 62 | return target 63 | 64 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/alternative_experiment_planning/target_spacing/experiment_planner_baseline_3DUNet_v21_customTargetSpacing_2x2x2.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | from nnformer.experiment_planning.experiment_planner_baseline_3DUNet_v21 import ExperimentPlanner3D_v21 17 | from nnformer.paths import * 18 | 19 | 20 | class ExperimentPlanner3D_v21_customTargetSpacing_2x2x2(ExperimentPlanner3D_v21): 21 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 22 | super(ExperimentPlanner3D_v21, self).__init__(folder_with_cropped_data, preprocessed_output_folder) 23 | # we change the data identifier and plans_fname. This will make this experiment planner save the preprocessed 24 | # data in a different folder so that they can co-exist with the default (ExperimentPlanner3D_v21). We also 25 | # create a custom plans file that will be linked to this data 26 | self.data_identifier = "nnFormerData_plans_v2.1_trgSp_2x2x2" 27 | self.plans_fname = join(self.preprocessed_output_folder, 28 | "nnFormerPlansv2.1_trgSp_2x2x2_plans_3D.pkl") 29 | 30 | def get_target_spacing(self): 31 | # simply return the desired spacing as np.array 32 | return np.array([2., 2., 2.]) # make sure this is float!!!! Not int! 33 | 34 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/change_batch_size.py: -------------------------------------------------------------------------------- 1 | from batchgenerators.utilities.file_and_folder_operations import * 2 | import numpy as np 3 | 4 | if __name__ == '__main__': 5 | input_file = '/home/xychen/new_transformer/nnFormerFrame/DATASET/nnFormer_preprocessed/Task008_Verse1/nnFormerPlansv2.1_plans_3D.pkl' 6 | output_file = '/home/xychen/new_transformer/nnFormerFrame/DATASET/nnFormer_preprocessed/Task008_Verse1/nnFormerPlansv2.1_plans_3D.pkl' 7 | a = load_pickle(input_file) 8 | #a['plans_per_stage'][0]['batch_size'] = int(np.floor(6 / 9 * a['plans_per_stage'][0]['batch_size'])) 9 | a['plans_per_stage'][0]['batch_size'] = 4 10 | save_pickle(a, output_file) -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/experiment_planner_baseline_2DUNet_v21.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from copy import deepcopy 15 | 16 | from nnformer.experiment_planning.common_utils import get_pool_and_conv_props 17 | from nnformer.experiment_planning.experiment_planner_baseline_2DUNet import ExperimentPlanner2D 18 | from nnformer.network_architecture.generic_UNet import Generic_UNet 19 | from nnformer.paths import * 20 | import numpy as np 21 | 22 | 23 | class ExperimentPlanner2D_v21(ExperimentPlanner2D): 24 | def __init__(self, folder_with_cropped_data, preprocessed_output_folder): 25 | super(ExperimentPlanner2D_v21, self).__init__(folder_with_cropped_data, preprocessed_output_folder) 26 | self.data_identifier = "nnFormerData_plans_v2.1_2D" 27 | self.plans_fname = join(self.preprocessed_output_folder, 28 | "nnFormerPlansv2.1_plans_2D.pkl") 29 | self.unet_base_num_features = 32 30 | 31 | def get_properties_for_stage(self, current_spacing, original_spacing, original_shape, num_cases, 32 | num_modalities, num_classes): 33 | 34 | new_median_shape = np.round(original_spacing / current_spacing * original_shape).astype(int) 35 | 36 | dataset_num_voxels = np.prod(new_median_shape, dtype=np.int64) * num_cases 37 | input_patch_size = new_median_shape[1:] 38 | 39 | network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ 40 | shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing[1:], input_patch_size, 41 | self.unet_featuremap_min_edge_length, 42 | self.unet_max_numpool) 43 | 44 | # we pretend to use 30 feature maps. This will yield the same configuration as in V1. The larger memory 45 | # footpring of 32 vs 30 is mor ethan offset by the fp16 training. We make fp16 training default 46 | # Reason for 32 vs 30 feature maps is that 32 is faster in fp16 training (because multiple of 8) 47 | ref = Generic_UNet.use_this_for_batch_size_computation_2D * Generic_UNet.DEFAULT_BATCH_SIZE_2D / 2 # for batch size 2 48 | here = Generic_UNet.compute_approx_vram_consumption(new_shp, 49 | network_num_pool_per_axis, 50 | 30, 51 | self.unet_max_num_filters, 52 | num_modalities, num_classes, 53 | pool_op_kernel_sizes, 54 | conv_per_stage=self.conv_per_stage) 55 | while here > ref: 56 | axis_to_be_reduced = np.argsort(new_shp / new_median_shape[1:])[-1] 57 | 58 | tmp = deepcopy(new_shp) 59 | tmp[axis_to_be_reduced] -= shape_must_be_divisible_by[axis_to_be_reduced] 60 | _, _, _, _, shape_must_be_divisible_by_new = \ 61 | get_pool_and_conv_props(current_spacing[1:], tmp, self.unet_featuremap_min_edge_length, 62 | self.unet_max_numpool) 63 | new_shp[axis_to_be_reduced] -= shape_must_be_divisible_by_new[axis_to_be_reduced] 64 | 65 | # we have to recompute numpool now: 66 | network_num_pool_per_axis, pool_op_kernel_sizes, conv_kernel_sizes, new_shp, \ 67 | shape_must_be_divisible_by = get_pool_and_conv_props(current_spacing[1:], new_shp, 68 | self.unet_featuremap_min_edge_length, 69 | self.unet_max_numpool) 70 | 71 | here = Generic_UNet.compute_approx_vram_consumption(new_shp, network_num_pool_per_axis, 72 | self.unet_base_num_features, 73 | self.unet_max_num_filters, num_modalities, 74 | num_classes, pool_op_kernel_sizes, 75 | conv_per_stage=self.conv_per_stage) 76 | # print(new_shp) 77 | 78 | batch_size = int(np.floor(ref / here) * 2) 79 | input_patch_size = new_shp 80 | 81 | if batch_size < self.unet_min_batch_size: 82 | raise RuntimeError("This should not happen") 83 | 84 | # check if batch size is too large (more than 5 % of dataset) 85 | max_batch_size = np.round(self.batch_size_covers_max_percent_of_dataset * dataset_num_voxels / 86 | np.prod(input_patch_size, dtype=np.int64)).astype(int) 87 | batch_size = max(1, min(batch_size, max_batch_size)) 88 | 89 | plan = { 90 | 'batch_size': batch_size, 91 | 'num_pool_per_axis': network_num_pool_per_axis, 92 | 'patch_size': input_patch_size, 93 | 'median_patient_size_in_voxels': new_median_shape, 94 | 'current_spacing': current_spacing, 95 | 'original_spacing': original_spacing, 96 | 'pool_op_kernel_sizes': pool_op_kernel_sizes, 97 | 'conv_kernel_sizes': conv_kernel_sizes, 98 | 'do_dummy_2D_data_aug': False 99 | } 100 | return plan 101 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/nnFormer_convert_decathlon_task.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | from batchgenerators.utilities.file_and_folder_operations import * 15 | from nnformer.configuration import default_num_threads 16 | from nnformer.experiment_planning.utils import split_4d 17 | from nnformer.utilities.file_endings import remove_trailing_slash 18 | 19 | 20 | def crawl_and_remove_hidden_from_decathlon(folder): 21 | folder = remove_trailing_slash(folder) 22 | assert folder.split('/')[-1].startswith("Task"), "This does not seem to be a decathlon folder. Please give me a " \ 23 | "folder that starts with TaskXX and has the subfolders imagesTr, " \ 24 | "labelsTr and imagesTs" 25 | subf = subfolders(folder, join=False) 26 | assert 'imagesTr' in subf, "This does not seem to be a decathlon folder. Please give me a " \ 27 | "folder that starts with TaskXX and has the subfolders imagesTr, " \ 28 | "labelsTr and imagesTs" 29 | assert 'imagesTs' in subf, "This does not seem to be a decathlon folder. Please give me a " \ 30 | "folder that starts with TaskXX and has the subfolders imagesTr, " \ 31 | "labelsTr and imagesTs" 32 | assert 'labelsTr' in subf, "This does not seem to be a decathlon folder. Please give me a " \ 33 | "folder that starts with TaskXX and has the subfolders imagesTr, " \ 34 | "labelsTr and imagesTs" 35 | _ = [os.remove(i) for i in subfiles(folder, prefix=".")] 36 | _ = [os.remove(i) for i in subfiles(join(folder, 'imagesTr'), prefix=".")] 37 | _ = [os.remove(i) for i in subfiles(join(folder, 'labelsTr'), prefix=".")] 38 | _ = [os.remove(i) for i in subfiles(join(folder, 'imagesTs'), prefix=".")] 39 | 40 | 41 | def main(): 42 | import argparse 43 | parser = argparse.ArgumentParser(description="The MSD provides data as 4D Niftis with the modality being the first" 44 | " dimension. We think this may be cumbersome for some users and " 45 | "therefore expect 3D niftixs instead, with one file per modality. " 46 | "This utility will convert 4D MSD data into the format nnU-Net " 47 | "expects") 48 | parser.add_argument("-i", help="Input folder. Must point to a TaskXX_TASKNAME folder as downloaded from the MSD " 49 | "website", required=True) 50 | parser.add_argument("-p", required=False, default=default_num_threads, type=int, 51 | help="Use this to specify how many processes are used to run the script. " 52 | "Default is %d" % default_num_threads) 53 | parser.add_argument("-output_task_id", required=False, default=None, type=int, 54 | help="If specified, this will overwrite the task id in the output folder. If unspecified, the " 55 | "task id of the input folder will be used.") 56 | args = parser.parse_args() 57 | 58 | crawl_and_remove_hidden_from_decathlon(args.i) 59 | 60 | split_4d(args.i, args.p, args.output_task_id) 61 | 62 | 63 | if __name__ == "__main__": 64 | main() 65 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/old/old_plan_and_preprocess_task.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from nnformer.experiment_planning.utils import split_4d, crop, analyze_dataset, plan_and_preprocess 16 | from batchgenerators.utilities.file_and_folder_operations import * 17 | from nnformer.paths import nnFormer_raw_data 18 | 19 | if __name__ == "__main__": 20 | import argparse 21 | parser = argparse.ArgumentParser() 22 | parser.add_argument('-t', '--task', type=str, help="task name. There must be a matching folder in " 23 | "raw_dataset_dir", required=True) 24 | parser.add_argument('-pl', '--processes_lowres', type=int, default=8, help='number of processes used for ' 25 | 'preprocessing 3d_lowres data, image ' 26 | 'splitting and image cropping ' 27 | 'Default: 8. The distinction between ' 28 | 'processes_lowres and processes_fullres ' 29 | 'is necessary because preprocessing ' 30 | 'at full resolution needs a lot of ' 31 | 'RAM', required=False) 32 | parser.add_argument('-pf', '--processes_fullres', type=int, default=8, help='number of processes used for ' 33 | 'preprocessing 2d and 3d_fullres ' 34 | 'data. Default: 3', required=False) 35 | parser.add_argument('-o', '--override', type=int, default=0, help="set this to 1 if you want to override " 36 | "cropped data and intensityproperties. Default: 0", 37 | required=False) 38 | parser.add_argument('-s', '--use_splitted', type=int, default=1, help='1 = use splitted data if already present (' 39 | 'skip split_4d). 0 = do splitting again. ' 40 | 'It is save to set this to 1 at all times ' 41 | 'unless the dataset was updated in the ' 42 | 'meantime. Default: 1', required=False) 43 | parser.add_argument('-no_preprocessing', type=int, default=0, help='debug only. If set to 1 this will run only' 44 | 'experiment planning and not run the ' 45 | 'preprocessing') 46 | 47 | args = parser.parse_args() 48 | task = args.task 49 | processes_lowres = args.processes_lowres 50 | processes_fullres = args.processes_fullres 51 | override = args.override 52 | use_splitted = args.use_splitted 53 | no_preprocessing = args.no_preprocessing 54 | 55 | if override == 0: 56 | override = False 57 | elif override == 1: 58 | override = True 59 | else: 60 | raise ValueError("only 0 or 1 allowed for override") 61 | 62 | if no_preprocessing == 0: 63 | no_preprocessing = False 64 | elif no_preprocessing == 1: 65 | no_preprocessing = True 66 | else: 67 | raise ValueError("only 0 or 1 allowed for override") 68 | 69 | if use_splitted == 0: 70 | use_splitted = False 71 | elif use_splitted == 1: 72 | use_splitted = True 73 | else: 74 | raise ValueError("only 0 or 1 allowed for use_splitted") 75 | 76 | if task == "all": 77 | all_tasks = subdirs(nnFormer_raw_data, prefix="Task", join=False) 78 | for t in all_tasks: 79 | crop(t, override=override, num_threads=processes_lowres) 80 | analyze_dataset(t, override=override, collect_intensityproperties=True, num_processes=processes_lowres) 81 | plan_and_preprocess(t, processes_lowres, processes_fullres, no_preprocessing) 82 | else: 83 | if not use_splitted or not isdir(join(nnFormer_raw_data, task)): 84 | print("splitting task ", task) 85 | split_4d(task) 86 | 87 | crop(task, override=override, num_threads=processes_lowres) 88 | analyze_dataset(task, override, collect_intensityproperties=True, num_processes=processes_lowres) 89 | plan_and_preprocess(task, processes_lowres, processes_fullres, no_preprocessing) 90 | -------------------------------------------------------------------------------- /ASA_Segmentation/experiment_planning/summarize_plans.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from batchgenerators.utilities.file_and_folder_operations import * 16 | from nnformer.paths import preprocessing_output_dir 17 | 18 | 19 | # This file is intended to double check nnFormers design choices. It is intended to be used for developent purposes only 20 | def summarize_plans(file): 21 | plans = load_pickle(file) 22 | print("num_classes: ", plans['num_classes']) 23 | print("modalities: ", plans['modalities']) 24 | print("use_mask_for_norm", plans['use_mask_for_norm']) 25 | print("keep_only_largest_region", plans['keep_only_largest_region']) 26 | print("min_region_size_per_class", plans['min_region_size_per_class']) 27 | print("min_size_per_class", plans['min_size_per_class']) 28 | print("normalization_schemes", plans['normalization_schemes']) 29 | print("stages...\n") 30 | 31 | for i in range(len(plans['plans_per_stage'])): 32 | print("stage: ", i) 33 | print(plans['plans_per_stage'][i]) 34 | print("") 35 | 36 | 37 | def write_plans_to_file(f, plans_file): 38 | print(plans_file) 39 | a = load_pickle(plans_file) 40 | stages = list(a['plans_per_stage'].keys()) 41 | stages.sort() 42 | for stage in stages: 43 | patch_size_in_mm = [i * j for i, j in zip(a['plans_per_stage'][stages[stage]]['patch_size'], 44 | a['plans_per_stage'][stages[stage]]['current_spacing'])] 45 | median_patient_size_in_mm = [i * j for i, j in zip(a['plans_per_stage'][stages[stage]]['median_patient_size_in_voxels'], 46 | a['plans_per_stage'][stages[stage]]['current_spacing'])] 47 | f.write(plans_file.split("/")[-2]) 48 | f.write(";%s" % plans_file.split("/")[-1]) 49 | f.write(";%d" % stage) 50 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['batch_size'])) 51 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['num_pool_per_axis'])) 52 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['patch_size'])) 53 | f.write(";%s" % str([str("%03.2f" % i) for i in patch_size_in_mm])) 54 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['median_patient_size_in_voxels'])) 55 | f.write(";%s" % str([str("%03.2f" % i) for i in median_patient_size_in_mm])) 56 | f.write(";%s" % str([str("%03.2f" % i) for i in a['plans_per_stage'][stages[stage]]['current_spacing']])) 57 | f.write(";%s" % str([str("%03.2f" % i) for i in a['plans_per_stage'][stages[stage]]['original_spacing']])) 58 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['pool_op_kernel_sizes'])) 59 | f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['conv_kernel_sizes'])) 60 | f.write(";%s" % str(a['data_identifier'])) 61 | f.write("\n") 62 | 63 | 64 | if __name__ == "__main__": 65 | base_dir = './'#preprocessing_output_dir'' 66 | task_dirs = [i for i in subdirs(base_dir, join=False, prefix="Task") if i.find("BrainTumor") == -1 and i.find("MSSeg") == -1] 67 | print("found %d tasks" % len(task_dirs)) 68 | 69 | with open("2019_02_06_plans_summary.csv", 'w') as f: 70 | f.write("task;plans_file;stage;batch_size;num_pool_per_axis;patch_size;patch_size(mm);median_patient_size_in_voxels;median_patient_size_in_mm;current_spacing;original_spacing;pool_op_kernel_sizes;conv_kernel_sizes\n") 71 | for t in task_dirs: 72 | print(t) 73 | tmp = join(base_dir, t) 74 | plans_files = [i for i in subfiles(tmp, suffix=".pkl", join=False) if i.find("_plans_") != -1 and i.find("Dgx2") == -1] 75 | for p in plans_files: 76 | write_plans_to_file(f, join(tmp, p)) 77 | f.write("\n") 78 | 79 | 80 | -------------------------------------------------------------------------------- /ASA_Segmentation/get_pretrain_ade.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | p1=['patch_embed.proj',"relative_position","downsample",'decode_head','auxiliary_head'] 5 | p2=['layers.2.blocks.%d'%i for i in range(18)[2:]] 6 | #if you use the imagenet pretrain weight, the p1 and p2 are as follows 7 | ''' 8 | p1=['patch_embed.proj',"relative_position","downsample",'attn_mask','head'] 9 | p2=['layers.2.blocks.%d'%i for i in range(18)[2:]] 10 | ''' 11 | pop_list=p1+p2 12 | 13 | 14 | def remove(): 15 | #input the pretrain weight of the swin transformer 16 | pretrained_dict = torch.load('./upernet_swin_small_patch4_window7_512x512.pth',map_location='cpu') 17 | weight=pretrained_dict['state_dict'] 18 | 19 | for i in list(weight.keys()): 20 | for j in pop_list: 21 | if j in i: 22 | weight.pop(i) 23 | break 24 | for i in weight: 25 | print(i) 26 | return weight 27 | 28 | def rename(weight): 29 | up_weight=weight.copy() 30 | for i in list(weight.keys()): 31 | weight.update({i.replace('backbone','model_down'):weight.pop(i)}) 32 | 33 | 34 | for i in list(up_weight.keys()): 35 | up_weight.update({i.replace('backbone','encoder'):up_weight.pop(i)}) 36 | 37 | weight.update(up_weight) 38 | #del unnecessary key in up_weight 39 | #the encoer name of our model is model_down 40 | #the decoder name of our model is encoer 41 | #haaa,I'm sorry for the mistake 42 | weight.pop('encoder.patch_embed.norm.weight') 43 | weight.pop('encoder.patch_embed.norm.bias') 44 | for i in list(weight): 45 | if 'encoder.layers.3' in i or 'encoder.norm' in i: 46 | weight.pop(i) 47 | 48 | return weight 49 | 50 | 51 | if __name__=='__main__': 52 | weight=remove() 53 | weight=rename(weight) 54 | #input one checkpoint of your model 55 | our_dict = torch.load("/model_best.model",map_location='cpu') 56 | our_weight=our_dict['state_dict'] 57 | 58 | for i in weight: 59 | our_weight[i]=weight[i] 60 | our_dict['state_dict']=our_weight 61 | torch.save(our_dict,'xxx.model') 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /ASA_Segmentation/inference/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/inference/change_trainer.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from batchgenerators.utilities.file_and_folder_operations import * 17 | 18 | 19 | def pretend_to_be_nnFormerTrainer(folder, checkpoints=("model_best.model.pkl", "model_final_checkpoint.model.pkl")): 20 | pretend_to_be_other_trainer(folder, "nnFormerTrainer", checkpoints) 21 | 22 | 23 | def pretend_to_be_other_trainer(folder, new_trainer_name, checkpoints=("model_best.model.pkl", "model_final_checkpoint.model.pkl")): 24 | folds = subdirs(folder, prefix="fold_", join=False) 25 | 26 | if isdir(join(folder, 'all')): 27 | folds.append('all') 28 | 29 | for c in checkpoints: 30 | for f in folds: 31 | checkpoint_file = join(folder, f, c) 32 | if isfile(checkpoint_file): 33 | a = load_pickle(checkpoint_file) 34 | a['name'] = new_trainer_name 35 | save_pickle(a, checkpoint_file) 36 | 37 | 38 | def main(): 39 | import argparse 40 | parser = argparse.ArgumentParser(description='Use this script to change the nnformer trainer class of a saved ' 41 | 'model. Useful for models that were trained with trainers that do ' 42 | 'not support inference (multi GPU trainers) or for trainer classes ' 43 | 'whose source code is not available. For this to work the network ' 44 | 'architecture must be identical between the original trainer ' 45 | 'class and the trainer class we are changing to. This script is ' 46 | 'experimental and only to be used by advanced users.') 47 | parser.add_argument('-i', help='Folder containing the trained model. This folder is the one containing the ' 48 | 'fold_X subfolders.') 49 | parser.add_argument('-tr', help='Name of the new trainer class') 50 | args = parser.parse_args() 51 | pretend_to_be_other_trainer(args.i, args.tr) 52 | -------------------------------------------------------------------------------- /ASA_Segmentation/inference/ensemble_predictions.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | import shutil 17 | from copy import deepcopy 18 | 19 | from nnformer.inference.segmentation_export import save_segmentation_nifti_from_softmax 20 | from batchgenerators.utilities.file_and_folder_operations import * 21 | import numpy as np 22 | from multiprocessing import Pool 23 | from nnformer.postprocessing.connected_components import apply_postprocessing_to_folder, load_postprocessing 24 | 25 | 26 | def merge_files(files, properties_files, out_file, override, store_npz): 27 | if override or not isfile(out_file): 28 | softmax = [np.load(f)['softmax'][None] for f in files] 29 | softmax = np.vstack(softmax) 30 | softmax = np.mean(softmax, 0) 31 | props = [load_pickle(f) for f in properties_files] 32 | 33 | reg_class_orders = [p['regions_class_order'] if 'regions_class_order' in p.keys() else None 34 | for p in props] 35 | 36 | if not all([i is None for i in reg_class_orders]): 37 | # if reg_class_orders are not None then they must be the same in all pkls 38 | tmp = reg_class_orders[0] 39 | for r in reg_class_orders[1:]: 40 | assert tmp == r, 'If merging files with regions_class_order, the regions_class_orders of all ' \ 41 | 'files must be the same. regions_class_order: %s, \n files: %s' % \ 42 | (str(reg_class_orders), str(files)) 43 | regions_class_order = tmp 44 | else: 45 | regions_class_order = None 46 | 47 | # Softmax probabilities are already at target spacing so this will not do any resampling (resampling parameters 48 | # don't matter here) 49 | save_segmentation_nifti_from_softmax(softmax, out_file, props[0], 3, regions_class_order, None, None, 50 | force_separate_z=None) 51 | if store_npz: 52 | np.savez_compressed(out_file[:-7] + ".npz", softmax=softmax) 53 | save_pickle(props, out_file[:-7] + ".pkl") 54 | 55 | 56 | def merge(folders, output_folder, threads, override=True, postprocessing_file=None, store_npz=False): 57 | maybe_mkdir_p(output_folder) 58 | 59 | if postprocessing_file is not None: 60 | output_folder_orig = deepcopy(output_folder) 61 | output_folder = join(output_folder, 'not_postprocessed') 62 | maybe_mkdir_p(output_folder) 63 | else: 64 | output_folder_orig = None 65 | 66 | patient_ids = [subfiles(i, suffix=".npz", join=False) for i in folders] 67 | patient_ids = [i for j in patient_ids for i in j] 68 | patient_ids = [i[:-4] for i in patient_ids] 69 | patient_ids = np.unique(patient_ids) 70 | 71 | for f in folders: 72 | assert all([isfile(join(f, i + ".npz")) for i in patient_ids]), "Not all patient npz are available in " \ 73 | "all folders" 74 | assert all([isfile(join(f, i + ".pkl")) for i in patient_ids]), "Not all patient pkl are available in " \ 75 | "all folders" 76 | 77 | files = [] 78 | property_files = [] 79 | out_files = [] 80 | for p in patient_ids: 81 | files.append([join(f, p + ".npz") for f in folders]) 82 | property_files.append([join(f, p + ".pkl") for f in folders]) 83 | out_files.append(join(output_folder, p + ".nii.gz")) 84 | 85 | p = Pool(threads) 86 | p.starmap(merge_files, zip(files, property_files, out_files, [override] * len(out_files), [store_npz] * len(out_files))) 87 | p.close() 88 | p.join() 89 | 90 | if postprocessing_file is not None: 91 | for_which_classes, min_valid_obj_size = load_postprocessing(postprocessing_file) 92 | print('Postprocessing...') 93 | apply_postprocessing_to_folder(output_folder, output_folder_orig, 94 | for_which_classes, min_valid_obj_size, threads) 95 | shutil.copy(postprocessing_file, output_folder_orig) 96 | 97 | 98 | def main(): 99 | import argparse 100 | parser = argparse.ArgumentParser(description="This script will merge predictions (that were prdicted with the " 101 | "-npz option!). You need to specify a postprocessing file so that " 102 | "we know here what postprocessing must be applied. Failing to do so " 103 | "will disable postprocessing") 104 | parser.add_argument('-f', '--folders', nargs='+', help="list of folders to merge. All folders must contain npz " 105 | "files", required=True) 106 | parser.add_argument('-o', '--output_folder', help="where to save the results", required=True, type=str) 107 | parser.add_argument('-t', '--threads', help="number of threads used to saving niftis", required=False, default=2, 108 | type=int) 109 | parser.add_argument('-pp', '--postprocessing_file', help="path to the file where the postprocessing configuration " 110 | "is stored. If this is not provided then no postprocessing " 111 | "will be made. It is strongly recommended to provide the " 112 | "postprocessing file!", 113 | required=False, type=str, default=None) 114 | parser.add_argument('--npz', action="store_true", required=False, help="stores npz and pkl") 115 | 116 | args = parser.parse_args() 117 | 118 | folders = args.folders 119 | threads = args.threads 120 | output_folder = args.output_folder 121 | pp_file = args.postprocessing_file 122 | npz = args.npz 123 | 124 | merge(folders, output_folder, threads, override=True, postprocessing_file=pp_file, store_npz=npz) 125 | 126 | 127 | if __name__ == "__main__": 128 | main() 129 | -------------------------------------------------------------------------------- /ASA_Segmentation/inference/inferTs/swin_nomask_2/plans.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lhaof/ASA/1f6295030d9370e23964ac4a3903ccedfb2315a9/ASA_Segmentation/inference/inferTs/swin_nomask_2/plans.pkl -------------------------------------------------------------------------------- /ASA_Segmentation/inference/pretrained_models/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/inference/pretrained_models/change_trainer.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from batchgenerators.utilities.file_and_folder_operations import * 17 | 18 | 19 | def pretend_to_be_nnFormerTrainer(folder, checkpoints=("model_best.model.pkl", "model_final_checkpoint.model.pkl")): 20 | pretend_to_be_other_trainer(folder, "nnFormerTrainer", checkpoints) 21 | 22 | 23 | def pretend_to_be_other_trainer(folder, new_trainer_name, checkpoints=("model_best.model.pkl", "model_final_checkpoint.model.pkl")): 24 | folds = subdirs(folder, prefix="fold_", join=False) 25 | 26 | if isdir(join(folder, 'all')): 27 | folds.append('all') 28 | 29 | for c in checkpoints: 30 | for f in folds: 31 | checkpoint_file = join(folder, f, c) 32 | if isfile(checkpoint_file): 33 | a = load_pickle(checkpoint_file) 34 | a['name'] = new_trainer_name 35 | save_pickle(a, checkpoint_file) 36 | 37 | 38 | def main(): 39 | import argparse 40 | parser = argparse.ArgumentParser(description='Use this script to change the nnformer trainer class of a saved ' 41 | 'model. Useful for models that were trained with trainers that do ' 42 | 'not support inference (multi GPU trainers) or for trainer classes ' 43 | 'whose source code is not available. For this to work the network ' 44 | 'architecture must be identical between the original trainer ' 45 | 'class and the trainer class we are changing to. This script is ' 46 | 'experimental and only to be used by advanced users.') 47 | parser.add_argument('-i', help='Folder containing the trained model. This folder is the one containing the ' 48 | 'fold_X subfolders.') 49 | parser.add_argument('-tr', help='Name of the new trainer class') 50 | args = parser.parse_args() 51 | pretend_to_be_other_trainer(args.i, args.tr) 52 | -------------------------------------------------------------------------------- /ASA_Segmentation/network_architecture/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/network_architecture/initialization.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from torch import nn 17 | 18 | 19 | class InitWeights_He(object): 20 | def __init__(self, neg_slope=1e-2): 21 | self.neg_slope = neg_slope 22 | 23 | def __call__(self, module): 24 | if isinstance(module, nn.Conv3d) or isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d) or isinstance(module, nn.ConvTranspose3d): 25 | module.weight = nn.init.kaiming_normal_(module.weight, a=self.neg_slope) 26 | if module.bias is not None: 27 | module.bias = nn.init.constant_(module.bias, 0) 28 | 29 | 30 | class InitWeights_XavierUniform(object): 31 | def __init__(self, gain=1): 32 | self.gain = gain 33 | 34 | def __call__(self, module): 35 | if isinstance(module, nn.Conv3d) or isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d) or isinstance(module, nn.ConvTranspose3d): 36 | module.weight = nn.init.xavier_uniform_(module.weight, self.gain) 37 | if module.bias is not None: 38 | module.bias = nn.init.constant_(module.bias, 0) 39 | -------------------------------------------------------------------------------- /ASA_Segmentation/paths.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import os 16 | from batchgenerators.utilities.file_and_folder_operations import maybe_mkdir_p, join 17 | 18 | # do not modify these unless you know what you are doing 19 | my_output_identifier = "nnFormer" 20 | default_plans_identifier = "nnFormerPlansv2.1" 21 | default_data_identifier = 'nnFormerData_plans_v2.1' 22 | default_trainer = "nnFormerTrainerV2" 23 | default_cascade_trainer = "nnFormerTrainerV2CascadeFullRes" 24 | 25 | """ 26 | PLEASE READ paths.md FOR INFORMATION TO HOW TO SET THIS UP 27 | """ 28 | 29 | base = os.environ['nnFormer_raw_data_base'] if "nnFormer_raw_data_base" in os.environ.keys() else None 30 | preprocessing_output_dir = os.environ['nnFormer_preprocessed'] if "nnFormer_preprocessed" in os.environ.keys() else None 31 | network_training_output_dir_base = os.path.join(os.environ['RESULTS_FOLDER_nnFormer']) if "RESULTS_FOLDER" in os.environ.keys() else None 32 | 33 | if base is not None: 34 | nnFormer_raw_data = join(base, "nnFormer_raw_data") 35 | nnFormer_cropped_data = join(base, "nnFormer_cropped_data") 36 | maybe_mkdir_p(nnFormer_raw_data) 37 | maybe_mkdir_p(nnFormer_cropped_data) 38 | else: 39 | print("nnFormer_raw_data_base is not defined and nnU-Net can only be used on data for which preprocessed files " 40 | "are already present on your system. nnU-Net cannot be used for experiment planning and preprocessing like " 41 | "this. If this is not intended, please read documentation/setting_up_paths.md for information on how to set this up properly.") 42 | nnFormer_cropped_data = nnFormer_raw_data = None 43 | 44 | if preprocessing_output_dir is not None: 45 | maybe_mkdir_p(preprocessing_output_dir) 46 | else: 47 | print("nnFormer_preprocessed is not defined and nnU-Net can not be used for preprocessing " 48 | "or training. If this is not intended, please read documentation/setting_up_paths.md for information on how to set this up.") 49 | preprocessing_output_dir = None 50 | 51 | if network_training_output_dir_base is not None: 52 | network_training_output_dir = join(network_training_output_dir_base, my_output_identifier) 53 | maybe_mkdir_p(network_training_output_dir) 54 | else: 55 | print("RESULTS_FOLDER is not defined and nnU-Net cannot be used for training or " 56 | "inference. If this is not intended behavior, please read documentation/setting_up_paths.md for information on how to set this " 57 | "up.") 58 | network_training_output_dir = None 59 | -------------------------------------------------------------------------------- /ASA_Segmentation/postprocessing/consolidate_all_for_paper.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from nnformer.utilities.folder_names import get_output_folder_name 17 | 18 | 19 | def get_datasets(): 20 | configurations_all = { 21 | "Task01_BrainTumour": ("3d_fullres", "2d"), 22 | "Task02_Heart": ("3d_fullres", "2d",), 23 | "Task03_Liver": ("3d_cascade_fullres", "3d_fullres", "3d_lowres", "2d"), 24 | "Task04_Hippocampus": ("3d_fullres", "2d",), 25 | "Task05_Prostate": ("3d_fullres", "2d",), 26 | "Task06_Lung": ("3d_cascade_fullres", "3d_fullres", "3d_lowres", "2d"), 27 | "Task07_Pancreas": ("3d_cascade_fullres", "3d_fullres", "3d_lowres", "2d"), 28 | "Task08_HepaticVessel": ("3d_cascade_fullres", "3d_fullres", "3d_lowres", "2d"), 29 | "Task09_Spleen": ("3d_cascade_fullres", "3d_fullres", "3d_lowres", "2d"), 30 | "Task10_Colon": ("3d_cascade_fullres", "3d_fullres", "3d_lowres", "2d"), 31 | "Task48_KiTS_clean": ("3d_cascade_fullres", "3d_lowres", "3d_fullres", "2d"), 32 | "Task27_ACDC": ("3d_fullres", "2d",), 33 | "Task24_Promise": ("3d_fullres", "2d",), 34 | "Task35_ISBILesionSegmentation": ("3d_fullres", "2d",), 35 | "Task38_CHAOS_Task_3_5_Variant2": ("3d_fullres", "2d",), 36 | "Task29_LITS": ("3d_cascade_fullres", "3d_lowres", "2d", "3d_fullres",), 37 | "Task17_AbdominalOrganSegmentation": ("3d_cascade_fullres", "3d_lowres", "2d", "3d_fullres",), 38 | "Task55_SegTHOR": ("3d_cascade_fullres", "3d_lowres", "3d_fullres", "2d",), 39 | "Task56_VerSe": ("3d_cascade_fullres", "3d_lowres", "3d_fullres", "2d",), 40 | } 41 | return configurations_all 42 | 43 | 44 | def get_commands(configurations, regular_trainer="nnFormerTrainerV2", cascade_trainer="nnFormerTrainerV2CascadeFullRes", 45 | plans="nnFormerPlansv2.1"): 46 | 47 | node_pool = ["hdf18-gpu%02.0d" % i for i in range(1, 21)] + ["hdf19-gpu%02.0d" % i for i in range(1, 8)] + ["hdf19-gpu%02.0d" % i for i in range(11, 16)] 48 | ctr = 0 49 | for task in configurations: 50 | models = configurations[task] 51 | for m in models: 52 | if m == "3d_cascade_fullres": 53 | trainer = cascade_trainer 54 | else: 55 | trainer = regular_trainer 56 | 57 | folder = get_output_folder_name(m, task, trainer, plans, overwrite_training_output_dir="/datasets/datasets_fabian/results/nnFormer") 58 | node = node_pool[ctr % len(node_pool)] 59 | print("bsub -m %s -q gputest -L /bin/bash \"source ~/.bashrc && python postprocessing/" 60 | "consolidate_postprocessing.py -f" % node, folder, "\"") 61 | ctr += 1 62 | -------------------------------------------------------------------------------- /ASA_Segmentation/postprocessing/consolidate_postprocessing.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import shutil 16 | from typing import Tuple 17 | 18 | from batchgenerators.utilities.file_and_folder_operations import * 19 | from nnformer.configuration import default_num_threads 20 | from nnformer.evaluation.evaluator import aggregate_scores 21 | from nnformer.postprocessing.connected_components import determine_postprocessing 22 | import argparse 23 | 24 | 25 | def collect_cv_niftis(cv_folder: str, output_folder: str, validation_folder_name: str = 'validation_raw', 26 | folds: tuple = (0, 1, 2, 3, 4)): 27 | validation_raw_folders = [join(cv_folder, "fold_%d" % i, validation_folder_name) for i in folds] 28 | exist = [isdir(i) for i in validation_raw_folders] 29 | 30 | if not all(exist): 31 | raise RuntimeError("some folds are missing. Please run the full 5-fold cross-validation. " 32 | "The following folds seem to be missing: %s" % 33 | [i for j, i in enumerate(folds) if not exist[j]]) 34 | 35 | # now copy all raw niftis into cv_niftis_raw 36 | maybe_mkdir_p(output_folder) 37 | for f in folds: 38 | niftis = subfiles(validation_raw_folders[f], suffix=".nii.gz") 39 | for n in niftis: 40 | shutil.copy(n, join(output_folder)) 41 | 42 | 43 | def consolidate_folds(output_folder_base, validation_folder_name: str = 'validation_raw', 44 | advanced_postprocessing: bool = False, folds: Tuple[int] = (0, 1, 2, 3, 4)): 45 | """ 46 | Used to determine the postprocessing for an experiment after all five folds have been completed. In the validation of 47 | each fold, the postprocessing can only be determined on the cases within that fold. This can result in different 48 | postprocessing decisions for different folds. In the end, we can only decide for one postprocessing per experiment, 49 | so we have to rerun it 50 | :param folds: 51 | :param advanced_postprocessing: 52 | :param output_folder_base:experiment output folder (fold_0, fold_1, etc must be subfolders of the given folder) 53 | :param validation_folder_name: dont use this 54 | :return: 55 | """ 56 | output_folder_raw = join(output_folder_base, "cv_niftis_raw") 57 | if isdir(output_folder_raw): 58 | shutil.rmtree(output_folder_raw) 59 | 60 | output_folder_gt = join(output_folder_base, "gt_niftis") 61 | collect_cv_niftis(output_folder_base, output_folder_raw, validation_folder_name, 62 | folds) 63 | 64 | num_niftis_gt = len(subfiles(join(output_folder_base, "gt_niftis"), suffix='.nii.gz')) 65 | # count niftis in there 66 | num_niftis = len(subfiles(output_folder_raw, suffix='.nii.gz')) 67 | if num_niftis != num_niftis_gt: 68 | raise AssertionError("If does not seem like you trained all the folds! Train all folds first!") 69 | 70 | # load a summary file so that we can know what class labels to expect 71 | summary_fold0 = load_json(join(output_folder_base, "fold_0", validation_folder_name, "summary.json"))['results'][ 72 | 'mean'] 73 | classes = [int(i) for i in summary_fold0.keys()] 74 | niftis = subfiles(output_folder_raw, join=False, suffix=".nii.gz") 75 | test_pred_pairs = [(join(output_folder_gt, i), join(output_folder_raw, i)) for i in niftis] 76 | 77 | # determine_postprocessing needs a summary.json file in the folder where the raw predictions are. We could compute 78 | # that from the summary files of the five folds but I am feeling lazy today 79 | aggregate_scores(test_pred_pairs, labels=classes, json_output_file=join(output_folder_raw, "summary.json"), 80 | num_threads=default_num_threads) 81 | 82 | determine_postprocessing(output_folder_base, output_folder_gt, 'cv_niftis_raw', 83 | final_subf_name="cv_niftis_postprocessed", processes=default_num_threads, 84 | advanced_postprocessing=advanced_postprocessing) 85 | # determine_postprocessing will create a postprocessing.json file that can be used for inference 86 | 87 | 88 | if __name__ == "__main__": 89 | argparser = argparse.ArgumentParser() 90 | argparser.add_argument("-f", type=str, required=True, help="experiment output folder (fold_0, fold_1, " 91 | "etc must be subfolders of the given folder)") 92 | 93 | args = argparser.parse_args() 94 | 95 | folder = args.f 96 | 97 | consolidate_folds(folder) 98 | -------------------------------------------------------------------------------- /ASA_Segmentation/postprocessing/consolidate_postprocessing_simple.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | import argparse 17 | from nnformer.postprocessing.consolidate_postprocessing import consolidate_folds 18 | from nnformer.utilities.folder_names import get_output_folder_name 19 | from nnformer.utilities.task_name_id_conversion import convert_id_to_task_name 20 | from nnformer.paths import default_cascade_trainer, default_trainer, default_plans_identifier 21 | 22 | 23 | def main(): 24 | argparser = argparse.ArgumentParser(usage="Used to determine the postprocessing for a trained model. Useful for " 25 | "when the best configuration (2d, 3d_fullres etc) as selected manually.") 26 | argparser.add_argument("-m", type=str, required=True, help="U-Net model (2d, 3d_lowres, 3d_fullres or " 27 | "3d_cascade_fullres)") 28 | argparser.add_argument("-t", type=str, required=True, help="Task name or id") 29 | argparser.add_argument("-tr", type=str, required=False, default=None, 30 | help="nnFormerTrainer class. Default: %s, unless 3d_cascade_fullres " 31 | "(then it's %s)" % (default_trainer, default_cascade_trainer)) 32 | argparser.add_argument("-pl", type=str, required=False, default=default_plans_identifier, 33 | help="Plans name, Default=%s" % default_plans_identifier) 34 | argparser.add_argument("-val", type=str, required=False, default="validation_raw", 35 | help="Validation folder name. Default: validation_raw") 36 | 37 | args = argparser.parse_args() 38 | model = args.m 39 | task = args.t 40 | trainer = args.tr 41 | plans = args.pl 42 | val = args.val 43 | 44 | if not task.startswith("Task"): 45 | task_id = int(task) 46 | task = convert_id_to_task_name(task_id) 47 | 48 | if trainer is None: 49 | if model == "3d_cascade_fullres": 50 | trainer = "nnFormerTrainerV2CascadeFullRes" 51 | else: 52 | trainer = "nnFormerTrainerV2" 53 | 54 | folder = get_output_folder_name(model, task, trainer, plans, None) 55 | 56 | consolidate_folds(folder, val) 57 | 58 | 59 | if __name__ == "__main__": 60 | main() 61 | -------------------------------------------------------------------------------- /ASA_Segmentation/preprocessing/custom_preprocessors/preprocessor_scale_RGB_to_0_1.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | from nnformer.preprocessing.preprocessing import PreprocessorFor2D, resample_patient 17 | 18 | 19 | class GenericPreprocessor_scale_uint8_to_0_1(PreprocessorFor2D): 20 | """ 21 | For RGB images with a value range of [0, 255]. This preprocessor overwrites the default normalization scheme by 22 | normalizing intensity values through a simple division by 255 which rescales them to [0, 1] 23 | 24 | NOTE THAT THIS INHERITS FROM PreprocessorFor2D, SO ITS WRITTEN FOR 2D ONLY! WHEN CREATING A PREPROCESSOR FOR 3D 25 | DATA, USE GenericPreprocessor AS PARENT! 26 | """ 27 | def resample_and_normalize(self, data, target_spacing, properties, seg=None, force_separate_z=None): 28 | ############ THIS PART IS IDENTICAL TO PARENT CLASS ################ 29 | 30 | original_spacing_transposed = np.array(properties["original_spacing"])[self.transpose_forward] 31 | before = { 32 | 'spacing': properties["original_spacing"], 33 | 'spacing_transposed': original_spacing_transposed, 34 | 'data.shape (data is transposed)': data.shape 35 | } 36 | target_spacing[0] = original_spacing_transposed[0] 37 | data, seg = resample_patient(data, seg, np.array(original_spacing_transposed), target_spacing, 3, 1, 38 | force_separate_z=force_separate_z, order_z_data=0, order_z_seg=0, 39 | separate_z_anisotropy_threshold=self.resample_separate_z_anisotropy_threshold) 40 | after = { 41 | 'spacing': target_spacing, 42 | 'data.shape (data is resampled)': data.shape 43 | } 44 | print("before:", before, "\nafter: ", after, "\n") 45 | 46 | if seg is not None: # hippocampus 243 has one voxel with -2 as label. wtf? 47 | seg[seg < -1] = 0 48 | 49 | properties["size_after_resampling"] = data[0].shape 50 | properties["spacing_after_resampling"] = target_spacing 51 | use_nonzero_mask = self.use_nonzero_mask 52 | 53 | assert len(self.normalization_scheme_per_modality) == len(data), "self.normalization_scheme_per_modality " \ 54 | "must have as many entries as data has " \ 55 | "modalities" 56 | assert len(self.use_nonzero_mask) == len(data), "self.use_nonzero_mask must have as many entries as data" \ 57 | " has modalities" 58 | 59 | print("normalization...") 60 | 61 | ############ HERE IS WHERE WE START CHANGING THINGS!!!!!!!################ 62 | 63 | # this is where the normalization takes place. We ignore use_nonzero_mask and normalization_scheme_per_modality 64 | for c in range(len(data)): 65 | data[c] = data[c].astype(np.float32) / 255. 66 | return data, seg, properties -------------------------------------------------------------------------------- /ASA_Segmentation/run/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/run/default_configuration.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | import nnformer 17 | from nnformer.paths import network_training_output_dir, preprocessing_output_dir, default_plans_identifier 18 | from batchgenerators.utilities.file_and_folder_operations import * 19 | from nnformer.experiment_planning.summarize_plans import summarize_plans 20 | from nnformer.training.model_restore import recursive_find_python_class 21 | import numpy as np 22 | import pickle 23 | 24 | 25 | def get_configuration_from_output_folder(folder): 26 | # split off network_training_output_dir 27 | folder = folder[len(network_training_output_dir):] 28 | if folder.startswith("/"): 29 | folder = folder[1:] 30 | 31 | configuration, task, trainer_and_plans_identifier = folder.split("/") 32 | trainer, plans_identifier = trainer_and_plans_identifier.split("__") 33 | return configuration, task, trainer, plans_identifier 34 | 35 | 36 | def get_default_configuration(network, task, network_trainer, plans_identifier=default_plans_identifier, 37 | search_in=(nnformer.__path__[0], "training", "network_training"), 38 | base_module='nnformer.training.network_training', tag='default'): 39 | assert network in ['2d', '3d_lowres', '3d_fullres', '3d_cascade_fullres'], \ 40 | "network can only be one of the following: \'3d\', \'3d_lowres\', \'3d_fullres\', \'3d_cascade_fullres\'" 41 | 42 | dataset_directory = join(preprocessing_output_dir, task) 43 | 44 | if network == '2d': 45 | plans_file = join(preprocessing_output_dir, task, plans_identifier + "_plans_2D.pkl") 46 | else: 47 | plans_file = join(preprocessing_output_dir, task, plans_identifier + "_plans_3D.pkl") 48 | 49 | plans = load_pickle(plans_file) 50 | if task == 'Task001_ACDC': 51 | plans['plans_per_stage'][0]['batch_size'] = 4 52 | plans['plans_per_stage'][0]['patch_size'] = np.array([14, 160, 160]) 53 | plans['plans_per_stage'][0]['pool_op_kernel_sizes'] = [[1, 2, 2], [1, 2, 2], [2, 2, 2], [2, 2, 2]] 54 | plans['plans_per_stage'][0]['conv_kernel_sizes'] = [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]] 55 | pickle_file = open(plans_file, 'wb') 56 | pickle.dump(plans, pickle_file) 57 | pickle_file.close() 58 | 59 | elif task == 'Task002_Synapse': 60 | plans['plans_per_stage'][1]['batch_size'] = 2 61 | plans['plans_per_stage'][1]['patch_size'] = np.array([64, 128, 128]) 62 | plans['plans_per_stage'][1]['pool_op_kernel_sizes'] = [[2, 2, 2], [2, 2, 2], [2, 2, 2], [2, 2, 2]] 63 | plans['plans_per_stage'][1]['conv_kernel_sizes'] = [[3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3], [3, 3, 3]] 64 | pickle_file = open(plans_file, 'wb') 65 | pickle.dump(plans, pickle_file) 66 | pickle_file.close() 67 | 68 | elif task == 'Task999_BraTS2021': 69 | plans['plans_per_stage'][0]['batch_size'] = 2 70 | plans['plans_per_stage'][0]['patch_size'] = np.array([128, 128, 128]) 71 | pickle_file = open(plans_file, 'wb') 72 | pickle.dump(plans, pickle_file) 73 | pickle_file.close() 74 | 75 | elif task == 'Task666_IBSR': 76 | plans['plans_per_stage'][0]['batch_size'] = 2 77 | plans['plans_per_stage'][0]['patch_size'] = np.array([128, 128, 128]) 78 | pickle_file = open(plans_file, 'wb') 79 | pickle.dump(plans, pickle_file) 80 | pickle_file.close() 81 | 82 | elif task == 'Task555_WMH': 83 | plans['plans_per_stage'][0]['batch_size'] = 2 84 | plans['plans_per_stage'][0]['patch_size'] = np.array([48, 128, 128]) 85 | pickle_file = open(plans_file, 'wb') 86 | pickle.dump(plans, pickle_file) 87 | pickle_file.close() 88 | 89 | possible_stages = list(plans['plans_per_stage'].keys()) 90 | 91 | if (network == '3d_cascade_fullres' or network == "3d_lowres") and len(possible_stages) == 1: 92 | raise RuntimeError("3d_lowres/3d_cascade_fullres only applies if there is more than one stage. This task does " 93 | "not require the cascade. Run 3d_fullres instead") 94 | 95 | if network == '2d' or network == "3d_lowres": 96 | stage = 0 97 | else: 98 | stage = possible_stages[-1] 99 | 100 | trainer_class = recursive_find_python_class([join(*search_in)], network_trainer, 101 | current_module=base_module) 102 | 103 | output_folder_name = join(network_training_output_dir, network, task, "Paper", network_trainer + "__" + tag) 104 | 105 | print("###############################################") 106 | print("I am running the following nnFormer: %s" % network) 107 | print("My trainer class is: ", trainer_class) 108 | print("For that I will be using the following configuration:") 109 | summarize_plans(plans_file) 110 | print("I am using stage %d from these plans" % stage) 111 | 112 | if (network == '2d' or len(possible_stages) > 1) and not network == '3d_lowres': 113 | batch_dice = True 114 | print("I am using batch dice + CE loss") 115 | else: 116 | batch_dice = False 117 | print("I am using sample dice + CE loss") 118 | 119 | print("\nI am using data from this folder: ", join(dataset_directory, plans['data_identifier'])) 120 | print("###############################################") 121 | return plans_file, output_folder_name, dataset_directory, batch_dice, stage, trainer_class 122 | -------------------------------------------------------------------------------- /ASA_Segmentation/run/load_pretrained_weights.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | import torch 15 | 16 | 17 | def load_pretrained_weights(network, fname, verbose=False): 18 | """ 19 | THIS DOES NOT TRANSFER SEGMENTATION HEADS! 20 | """ 21 | saved_model = torch.load(fname) 22 | pretrained_dict = saved_model['state_dict'] 23 | 24 | new_state_dict = {} 25 | 26 | # if state dict comes form nn.DataParallel but we use non-parallel model here then the state dict keys do not 27 | # match. Use heuristic to make it match 28 | for k, value in pretrained_dict.items(): 29 | key = k 30 | # remove module. prefix from DDP models 31 | if key.startswith('module.'): 32 | key = key[7:] 33 | new_state_dict[key] = value 34 | 35 | pretrained_dict = new_state_dict 36 | 37 | model_dict = network.state_dict() 38 | ok = True 39 | for key, _ in model_dict.items(): 40 | if ('conv_blocks' in key): 41 | if (key in pretrained_dict) and (model_dict[key].shape == pretrained_dict[key].shape): 42 | continue 43 | else: 44 | ok = False 45 | break 46 | 47 | # filter unnecessary keys 48 | if ok: 49 | pretrained_dict = {k: v for k, v in pretrained_dict.items() if 50 | (k in model_dict) and (model_dict[k].shape == pretrained_dict[k].shape)} 51 | # 2. overwrite entries in the existing state dict 52 | model_dict.update(pretrained_dict) 53 | print("################### Loading pretrained weights from file ", fname, '###################') 54 | if verbose: 55 | print("Below is the list of overlapping blocks in pretrained model and nnFormer architecture:") 56 | for key, _ in pretrained_dict.items(): 57 | print(key) 58 | print("################### Done ###################") 59 | network.load_state_dict(model_dict) 60 | else: 61 | raise RuntimeError("Pretrained weights are not compatible with the current network architecture") 62 | 63 | -------------------------------------------------------------------------------- /ASA_Segmentation/training/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/training/cascade_stuff/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/training/data_augmentation/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/training/data_augmentation/custom_transforms.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | from batchgenerators.transforms import AbstractTransform 17 | 18 | 19 | class RemoveKeyTransform(AbstractTransform): 20 | def __init__(self, key_to_remove): 21 | self.key_to_remove = key_to_remove 22 | 23 | def __call__(self, **data_dict): 24 | _ = data_dict.pop(self.key_to_remove, None) 25 | return data_dict 26 | 27 | 28 | class MaskTransform(AbstractTransform): 29 | def __init__(self, dct_for_where_it_was_used, mask_idx_in_seg=1, set_outside_to=0, data_key="data", seg_key="seg"): 30 | """ 31 | data[mask < 0] = 0 32 | Sets everything outside the mask to 0. CAREFUL! outside is defined as < 0, not =0 (in the Mask)!!! 33 | 34 | :param dct_for_where_it_was_used: 35 | :param mask_idx_in_seg: 36 | :param set_outside_to: 37 | :param data_key: 38 | :param seg_key: 39 | """ 40 | self.dct_for_where_it_was_used = dct_for_where_it_was_used 41 | self.seg_key = seg_key 42 | self.data_key = data_key 43 | self.set_outside_to = set_outside_to 44 | self.mask_idx_in_seg = mask_idx_in_seg 45 | 46 | def __call__(self, **data_dict): 47 | seg = data_dict.get(self.seg_key) 48 | if seg is None or seg.shape[1] < self.mask_idx_in_seg: 49 | raise Warning("mask not found, seg may be missing or seg[:, mask_idx_in_seg] may not exist") 50 | data = data_dict.get(self.data_key) 51 | for b in range(data.shape[0]): 52 | mask = seg[b, self.mask_idx_in_seg] 53 | for c in range(data.shape[1]): 54 | if self.dct_for_where_it_was_used[c]: 55 | data[b, c][mask < 0] = self.set_outside_to 56 | data_dict[self.data_key] = data 57 | return data_dict 58 | 59 | 60 | def convert_3d_to_2d_generator(data_dict): 61 | shp = data_dict['data'].shape 62 | data_dict['data'] = data_dict['data'].reshape((shp[0], shp[1] * shp[2], shp[3], shp[4])) 63 | data_dict['orig_shape_data'] = shp 64 | shp = data_dict['seg'].shape 65 | data_dict['seg'] = data_dict['seg'].reshape((shp[0], shp[1] * shp[2], shp[3], shp[4])) 66 | data_dict['orig_shape_seg'] = shp 67 | return data_dict 68 | 69 | 70 | def convert_2d_to_3d_generator(data_dict): 71 | shp = data_dict['orig_shape_data'] 72 | current_shape = data_dict['data'].shape 73 | data_dict['data'] = data_dict['data'].reshape((shp[0], shp[1], shp[2], current_shape[-2], current_shape[-1])) 74 | shp = data_dict['orig_shape_seg'] 75 | current_shape_seg = data_dict['seg'].shape 76 | data_dict['seg'] = data_dict['seg'].reshape((shp[0], shp[1], shp[2], current_shape_seg[-2], current_shape_seg[-1])) 77 | return data_dict 78 | 79 | 80 | class Convert3DTo2DTransform(AbstractTransform): 81 | def __init__(self): 82 | pass 83 | 84 | def __call__(self, **data_dict): 85 | return convert_3d_to_2d_generator(data_dict) 86 | 87 | 88 | class Convert2DTo3DTransform(AbstractTransform): 89 | def __init__(self): 90 | pass 91 | 92 | def __call__(self, **data_dict): 93 | return convert_2d_to_3d_generator(data_dict) 94 | 95 | 96 | class ConvertSegmentationToRegionsTransform(AbstractTransform): 97 | def __init__(self, regions: dict, seg_key: str = "seg", output_key: str = "seg", seg_channel: int = 0): 98 | """ 99 | regions are tuple of tuples where each inner tuple holds the class indices that are merged into one region, example: 100 | regions= ((1, 2), (2, )) will result in 2 regions: one covering the region of labels 1&2 and the other just 2 101 | :param regions: 102 | :param seg_key: 103 | :param output_key: 104 | """ 105 | self.seg_channel = seg_channel 106 | self.output_key = output_key 107 | self.seg_key = seg_key 108 | self.regions = regions 109 | 110 | def __call__(self, **data_dict): 111 | seg = data_dict.get(self.seg_key) 112 | num_regions = len(self.regions) 113 | if seg is not None: 114 | seg_shp = seg.shape 115 | output_shape = list(seg_shp) 116 | output_shape[1] = num_regions 117 | region_output = np.zeros(output_shape, dtype=seg.dtype) 118 | for b in range(seg_shp[0]): 119 | for r, k in enumerate(self.regions.keys()): 120 | for l in self.regions[k]: 121 | region_output[b, r][seg[b, self.seg_channel] == l] = 1 122 | data_dict[self.output_key] = region_output 123 | return data_dict 124 | -------------------------------------------------------------------------------- /ASA_Segmentation/training/data_augmentation/data_augmentation_noDA.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from batchgenerators.dataloading import MultiThreadedAugmenter 16 | from batchgenerators.transforms import DataChannelSelectionTransform, SegChannelSelectionTransform, Compose 17 | from batchgenerators.transforms.utility_transforms import RemoveLabelTransform, RenameTransform, NumpyToTensor 18 | from nnformer.training.data_augmentation.custom_transforms import ConvertSegmentationToRegionsTransform 19 | from nnformer.training.data_augmentation.default_data_augmentation import default_3D_augmentation_params 20 | from nnformer.training.data_augmentation.downsampling import DownsampleSegForDSTransform3, DownsampleSegForDSTransform2 21 | 22 | try: 23 | from batchgenerators.dataloading.nondet_multi_threaded_augmenter import NonDetMultiThreadedAugmenter 24 | except ImportError as ie: 25 | NonDetMultiThreadedAugmenter = None 26 | 27 | 28 | def get_no_augmentation(dataloader_train, dataloader_val, params=default_3D_augmentation_params, 29 | deep_supervision_scales=None, soft_ds=False, 30 | classes=None, pin_memory=True, regions=None): 31 | """ 32 | use this instead of get_default_augmentation (drop in replacement) to turn off all data augmentation 33 | """ 34 | tr_transforms = [] 35 | 36 | if params.get("selected_data_channels") is not None: 37 | tr_transforms.append(DataChannelSelectionTransform(params.get("selected_data_channels"))) 38 | 39 | if params.get("selected_seg_channels") is not None: 40 | tr_transforms.append(SegChannelSelectionTransform(params.get("selected_seg_channels"))) 41 | 42 | tr_transforms.append(RemoveLabelTransform(-1, 0)) 43 | 44 | tr_transforms.append(RenameTransform('seg', 'target', True)) 45 | 46 | if regions is not None: 47 | tr_transforms.append(ConvertSegmentationToRegionsTransform(regions, 'target', 'target')) 48 | 49 | if deep_supervision_scales is not None: 50 | if soft_ds: 51 | assert classes is not None 52 | tr_transforms.append(DownsampleSegForDSTransform3(deep_supervision_scales, 'target', 'target', classes)) 53 | else: 54 | tr_transforms.append(DownsampleSegForDSTransform2(deep_supervision_scales, 0, 0, input_key='target', 55 | output_key='target')) 56 | 57 | tr_transforms.append(NumpyToTensor(['data', 'target'], 'float')) 58 | 59 | tr_transforms = Compose(tr_transforms) 60 | 61 | batchgenerator_train = MultiThreadedAugmenter(dataloader_train, tr_transforms, params.get('num_threads'), 62 | params.get("num_cached_per_thread"), 63 | seeds=range(params.get('num_threads')), pin_memory=pin_memory) 64 | batchgenerator_train.restart() 65 | 66 | val_transforms = [] 67 | val_transforms.append(RemoveLabelTransform(-1, 0)) 68 | if params.get("selected_data_channels") is not None: 69 | val_transforms.append(DataChannelSelectionTransform(params.get("selected_data_channels"))) 70 | if params.get("selected_seg_channels") is not None: 71 | val_transforms.append(SegChannelSelectionTransform(params.get("selected_seg_channels"))) 72 | 73 | val_transforms.append(RenameTransform('seg', 'target', True)) 74 | 75 | if regions is not None: 76 | val_transforms.append(ConvertSegmentationToRegionsTransform(regions, 'target', 'target')) 77 | 78 | if deep_supervision_scales is not None: 79 | if soft_ds: 80 | assert classes is not None 81 | val_transforms.append(DownsampleSegForDSTransform3(deep_supervision_scales, 'target', 'target', classes)) 82 | else: 83 | val_transforms.append(DownsampleSegForDSTransform2(deep_supervision_scales, 0, 0, input_key='target', 84 | output_key='target')) 85 | 86 | val_transforms.append(NumpyToTensor(['data', 'target'], 'float')) 87 | val_transforms = Compose(val_transforms) 88 | 89 | batchgenerator_val = MultiThreadedAugmenter(dataloader_val, val_transforms, max(params.get('num_threads') // 2, 1), 90 | params.get("num_cached_per_thread"), 91 | seeds=range(max(params.get('num_threads') // 2, 1)), 92 | pin_memory=pin_memory) 93 | batchgenerator_val.restart() 94 | return batchgenerator_train, batchgenerator_val 95 | 96 | -------------------------------------------------------------------------------- /ASA_Segmentation/training/data_augmentation/downsampling.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | import torch 17 | from batchgenerators.augmentations.utils import convert_seg_image_to_one_hot_encoding_batched, resize_segmentation 18 | from batchgenerators.transforms import AbstractTransform 19 | from torch.nn.functional import avg_pool2d, avg_pool3d 20 | import numpy as np 21 | 22 | 23 | class DownsampleSegForDSTransform3(AbstractTransform): 24 | ''' 25 | returns one hot encodings of the segmentation maps if downsampling has occured (no one hot for highest resolution) 26 | downsampled segmentations are smooth, not 0/1 27 | 28 | returns torch tensors, not numpy arrays! 29 | 30 | always uses seg channel 0!! 31 | 32 | you should always give classes! Otherwise weird stuff may happen 33 | ''' 34 | def __init__(self, ds_scales=(1, 0.5, 0.25), input_key="seg", output_key="seg", classes=None): 35 | self.classes = classes 36 | self.output_key = output_key 37 | self.input_key = input_key 38 | self.ds_scales = ds_scales 39 | 40 | def __call__(self, **data_dict): 41 | data_dict[self.output_key] = downsample_seg_for_ds_transform3(data_dict[self.input_key][:, 0], self.ds_scales, self.classes) 42 | return data_dict 43 | 44 | 45 | def downsample_seg_for_ds_transform3(seg, ds_scales=((1, 1, 1), (0.5, 0.5, 0.5), (0.25, 0.25, 0.25)), classes=None): 46 | output = [] 47 | one_hot = torch.from_numpy(convert_seg_image_to_one_hot_encoding_batched(seg, classes)) # b, c, 48 | 49 | for s in ds_scales: 50 | if all([i == 1 for i in s]): 51 | output.append(torch.from_numpy(seg)) 52 | else: 53 | kernel_size = tuple(int(1 / i) for i in s) 54 | stride = kernel_size 55 | pad = tuple((i-1) // 2 for i in kernel_size) 56 | 57 | if len(s) == 2: 58 | pool_op = avg_pool2d 59 | elif len(s) == 3: 60 | pool_op = avg_pool3d 61 | else: 62 | raise RuntimeError() 63 | 64 | pooled = pool_op(one_hot, kernel_size, stride, pad, count_include_pad=False, ceil_mode=False) 65 | 66 | output.append(pooled) 67 | return output 68 | 69 | 70 | class DownsampleSegForDSTransform2(AbstractTransform): 71 | ''' 72 | data_dict['output_key'] will be a list of segmentations scaled according to ds_scales 73 | ''' 74 | def __init__(self, ds_scales=(1, 0.5, 0.25), order=0, cval=0, input_key="seg", output_key="seg", axes=None): 75 | self.axes = axes 76 | self.output_key = output_key 77 | self.input_key = input_key 78 | self.cval = cval 79 | self.order = order 80 | self.ds_scales = ds_scales 81 | 82 | def __call__(self, **data_dict): 83 | data_dict[self.output_key] = downsample_seg_for_ds_transform2(data_dict[self.input_key], self.ds_scales, self.order, 84 | self.cval, self.axes) 85 | return data_dict 86 | 87 | 88 | def downsample_seg_for_ds_transform2(seg, ds_scales=((1, 1, 1), (0.5, 0.5, 0.5), (0.25, 0.25, 0.25)), order=0, cval=0, axes=None): 89 | if axes is None: 90 | axes = list(range(2, len(seg.shape))) 91 | output = [] 92 | for s in ds_scales: 93 | if all([i == 1 for i in s]): 94 | output.append(seg) 95 | else: 96 | new_shape = np.array(seg.shape).astype(float) 97 | for i, a in enumerate(axes): 98 | new_shape[a] *= s[i] 99 | new_shape = np.round(new_shape).astype(int) 100 | out_seg = np.zeros(new_shape, dtype=seg.dtype) 101 | for b in range(seg.shape[0]): 102 | for c in range(seg.shape[1]): 103 | out_seg[b, c] = resize_segmentation(seg[b, c], new_shape[2:], order, cval) 104 | output.append(out_seg) 105 | return output 106 | -------------------------------------------------------------------------------- /ASA_Segmentation/training/dataloading/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/training/learning_rate/poly_lr.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | def poly_lr(epoch, max_epochs, initial_lr, exponent=0.9): 17 | return initial_lr * (1 - epoch / max_epochs)**exponent 18 | -------------------------------------------------------------------------------- /ASA_Segmentation/training/loss_functions/TopK_loss.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | import torch 17 | from nnformer.training.loss_functions.crossentropy import RobustCrossEntropyLoss 18 | 19 | 20 | class TopKLoss(RobustCrossEntropyLoss): 21 | """ 22 | Network has to have NO LINEARITY! 23 | """ 24 | def __init__(self, weight=None, ignore_index=-100, k=10): 25 | self.k = k 26 | super(TopKLoss, self).__init__(weight, False, ignore_index, reduce=False) 27 | 28 | def forward(self, inp, target): 29 | target = target[:, 0].long() 30 | res = super(TopKLoss, self).forward(inp, target) 31 | num_voxels = np.prod(res.shape, dtype=np.int64) 32 | res, _ = torch.topk(res.view((-1, )), int(num_voxels * self.k / 100), sorted=False) 33 | return res.mean() 34 | -------------------------------------------------------------------------------- /ASA_Segmentation/training/loss_functions/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/training/loss_functions/crossentropy.py: -------------------------------------------------------------------------------- 1 | from torch import nn, Tensor 2 | 3 | 4 | class RobustCrossEntropyLoss(nn.CrossEntropyLoss): 5 | """ 6 | this is just a compatibility layer because my target tensor is float and has an extra dimension 7 | """ 8 | def forward(self, input: Tensor, target: Tensor) -> Tensor: 9 | if len(target.shape) == len(input.shape): 10 | assert target.shape[1] == 1 11 | target = target[:, 0] 12 | return super().forward(input, target.long()) -------------------------------------------------------------------------------- /ASA_Segmentation/training/loss_functions/deep_supervision.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from torch import nn 17 | 18 | 19 | class MultipleOutputLoss2(nn.Module): 20 | def __init__(self, loss, weight_factors=None): 21 | """ 22 | use this if you have several outputs and ground truth (both list of same len) and the loss should be computed 23 | between them (x[0] and y[0], x[1] and y[1] etc) 24 | :param loss: 25 | :param weight_factors: 26 | """ 27 | super(MultipleOutputLoss2, self).__init__() 28 | self.weight_factors = weight_factors 29 | self.loss = loss 30 | 31 | def forward(self, x, y): 32 | assert isinstance(x, (tuple, list)), "x must be either tuple or list" 33 | assert isinstance(y, (tuple, list)), "y must be either tuple or list" 34 | if self.weight_factors is None: 35 | weights = [1] * len(x) 36 | else: 37 | weights = self.weight_factors 38 | 39 | l = weights[0] * self.loss(x[0], y[0]) 40 | for i in range(1, len(x)): 41 | if weights[i] != 0: 42 | l += weights[i] * self.loss(x[i], y[i]) 43 | return l 44 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from . import * -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/distributed.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | import torch 17 | from torch import distributed 18 | from torch import autograd 19 | from torch.nn.parallel import DistributedDataParallel as DDP 20 | 21 | 22 | def print_if_rank0(*args): 23 | if distributed.get_rank() == 0: 24 | print(*args) 25 | 26 | 27 | class awesome_allgather_function(autograd.Function): 28 | @staticmethod 29 | def forward(ctx, input): 30 | world_size = distributed.get_world_size() 31 | # create a destination list for the allgather. I'm assuming you're gathering from 3 workers. 32 | allgather_list = [torch.empty_like(input) for _ in range(world_size)] 33 | #if distributed.get_rank() == 0: 34 | # import IPython;IPython.embed() 35 | distributed.all_gather(allgather_list, input) 36 | return torch.cat(allgather_list, dim=0) 37 | 38 | @staticmethod 39 | def backward(ctx, grad_output): 40 | #print_if_rank0("backward grad_output len", len(grad_output)) 41 | #print_if_rank0("backward grad_output shape", grad_output.shape) 42 | grads_per_rank = grad_output.shape[0] // distributed.get_world_size() 43 | rank = distributed.get_rank() 44 | # We'll receive gradients for the entire catted forward output, so to mimic DataParallel, 45 | # return only the slice that corresponds to this process's input: 46 | sl = slice(rank * grads_per_rank, (rank + 1) * grads_per_rank) 47 | #print("worker", rank, "backward slice", sl) 48 | return grad_output[sl] 49 | 50 | 51 | if __name__ == "__main__": 52 | import torch.distributed as dist 53 | import argparse 54 | from torch import nn 55 | from torch.optim import Adam 56 | 57 | argumentparser = argparse.ArgumentParser() 58 | argumentparser.add_argument("--local_rank", type=int) 59 | args = argumentparser.parse_args() 60 | 61 | torch.cuda.set_device(args.local_rank) 62 | dist.init_process_group(backend='nccl', init_method='env://') 63 | 64 | rnd = torch.rand((5, 2)).cuda() 65 | 66 | rnd_gathered = awesome_allgather_function.apply(rnd) 67 | print("gathering random tensors\nbefore\b", rnd, "\nafter\n", rnd_gathered) 68 | 69 | # so far this works as expected 70 | print("now running a DDP model") 71 | c = nn.Conv2d(2, 3, 3, 1, 1, 1, 1, True).cuda() 72 | c = DDP(c) 73 | opt = Adam(c.parameters()) 74 | 75 | bs = 5 76 | if dist.get_rank() == 0: 77 | bs = 4 78 | inp = torch.rand((bs, 2, 5, 5)).cuda() 79 | 80 | out = c(inp) 81 | print("output_shape", out.shape) 82 | 83 | out_gathered = awesome_allgather_function.apply(out) 84 | print("output_shape_after_gather", out_gathered.shape) 85 | # this also works 86 | 87 | loss = out_gathered.sum() 88 | loss.backward() 89 | opt.step() 90 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/file_conversions.py: -------------------------------------------------------------------------------- 1 | from typing import Tuple, List, Union 2 | from skimage import io 3 | import SimpleITK as sitk 4 | import numpy as np 5 | import tifffile 6 | 7 | 8 | def convert_2d_image_to_nifti(input_filename: str, output_filename_truncated: str, spacing=(999, 1, 1), 9 | transform=None, is_seg: bool = False) -> None: 10 | """ 11 | Reads an image (must be a format that it recognized by skimage.io.imread) and converts it into a series of niftis. 12 | The image can have an arbitrary number of input channels which will be exported separately (_0000.nii.gz, 13 | _0001.nii.gz, etc for images and only .nii.gz for seg). 14 | Spacing can be ignored most of the time. 15 | !!!2D images are often natural images which do not have a voxel spacing that could be used for resampling. These images 16 | must be resampled by you prior to converting them to nifti!!! 17 | 18 | Datasets converted with this utility can only be used with the 2d U-Net configuration of nnU-Net 19 | 20 | If Transform is not None it will be applied to the image after loading. 21 | 22 | Segmentations will be converted to np.uint32! 23 | 24 | :param is_seg: 25 | :param transform: 26 | :param input_filename: 27 | :param output_filename_truncated: do not use a file ending for this one! Example: output_name='./converted/image1'. This 28 | function will add the suffix (_0000) and file ending (.nii.gz) for you. 29 | :param spacing: 30 | :return: 31 | """ 32 | img = io.imread(input_filename) 33 | 34 | if transform is not None: 35 | img = transform(img) 36 | 37 | if len(img.shape) == 2: # 2d image with no color channels 38 | img = img[None, None] # add dimensions 39 | else: 40 | assert len(img.shape) == 3, "image should be 3d with color channel last but has shape %s" % str(img.shape) 41 | # we assume that the color channel is the last dimension. Transpose it to be in first 42 | img = img.transpose((2, 0, 1)) 43 | # add third dimension 44 | img = img[:, None] 45 | 46 | # image is now (c, x, x, z) where x=1 since it's 2d 47 | if is_seg: 48 | assert img.shape[0] == 1, 'segmentations can only have one color channel, not sure what happened here' 49 | 50 | for j, i in enumerate(img): 51 | 52 | if is_seg: 53 | i = i.astype(np.uint32) 54 | 55 | itk_img = sitk.GetImageFromArray(i) 56 | itk_img.SetSpacing(list(spacing)[::-1]) 57 | if not is_seg: 58 | sitk.WriteImage(itk_img, output_filename_truncated + "_%04.0d.nii.gz" % j) 59 | else: 60 | sitk.WriteImage(itk_img, output_filename_truncated + ".nii.gz") 61 | 62 | 63 | def convert_3d_tiff_to_nifti(filenames: List[str], output_name: str, spacing: Union[tuple, list], transform=None, is_seg=False) -> None: 64 | """ 65 | filenames must be a list of strings, each pointing to a separate 3d tiff file. One file per modality. If your data 66 | only has one imaging modality, simply pass a list with only a single entry 67 | 68 | Files in filenames must be readable with 69 | 70 | Note: we always only pass one file into tifffile.imread, not multiple (even though it supports it). This is because 71 | I am not familiar enough with this functionality and would like to have control over what happens. 72 | 73 | If Transform is not None it will be applied to the image after loading. 74 | 75 | :param transform: 76 | :param filenames: 77 | :param output_name: 78 | :param spacing: 79 | :return: 80 | """ 81 | if is_seg: 82 | assert len(filenames) == 1 83 | 84 | for j, i in enumerate(filenames): 85 | img = tifffile.imread(i) 86 | 87 | if transform is not None: 88 | img = transform(img) 89 | 90 | itk_img = sitk.GetImageFromArray(img) 91 | itk_img.SetSpacing(list(spacing)[::-1]) 92 | 93 | if not is_seg: 94 | sitk.WriteImage(itk_img, output_name + "_%04.0d.nii.gz" % j) 95 | else: 96 | sitk.WriteImage(itk_img, output_name + ".nii.gz") 97 | 98 | 99 | def convert_2d_segmentation_nifti_to_img(nifti_file: str, output_filename: str, transform=None, export_dtype=np.uint8): 100 | img = sitk.GetArrayFromImage(sitk.ReadImage(nifti_file)) 101 | assert img.shape[0] == 1, "This function can only export 2D segmentations!" 102 | img = img[0] 103 | if transform is not None: 104 | img = transform(img) 105 | 106 | io.imsave(output_filename, img.astype(export_dtype), check_contrast=False) 107 | 108 | 109 | def convert_3d_segmentation_nifti_to_tiff(nifti_file: str, output_filename: str, transform=None, export_dtype=np.uint8): 110 | img = sitk.GetArrayFromImage(sitk.ReadImage(nifti_file)) 111 | assert len(img.shape) == 3, "This function can only export 3D segmentations!" 112 | if transform is not None: 113 | img = transform(img) 114 | 115 | tifffile.imsave(output_filename, img.astype(export_dtype)) 116 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/file_endings.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from batchgenerators.utilities.file_and_folder_operations import * 17 | 18 | 19 | def remove_trailing_slash(filename: str): 20 | while filename.endswith('/'): 21 | filename = filename[:-1] 22 | return filename 23 | 24 | 25 | def maybe_add_0000_to_all_niigz(folder): 26 | nii_gz = subfiles(folder, suffix='.nii.gz') 27 | for n in nii_gz: 28 | n = remove_trailing_slash(n) 29 | if not n.endswith('_0000.nii.gz'): 30 | os.rename(n, n[:-7] + '_0000.nii.gz') 31 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/folder_names.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from batchgenerators.utilities.file_and_folder_operations import * 17 | from nnformer.paths import network_training_output_dir 18 | 19 | 20 | def get_output_folder_name(model: str, task: str = None, trainer: str = None, plans: str = None, fold: int = None, 21 | overwrite_training_output_dir: str = None): 22 | """ 23 | Retrieves the correct output directory for the nnU-Net model described by the input parameters 24 | 25 | :param model: 26 | :param task: 27 | :param trainer: 28 | :param plans: 29 | :param fold: 30 | :param overwrite_training_output_dir: 31 | :return: 32 | """ 33 | assert model in ["2d", "3d_cascade_fullres", '3d_fullres', '3d_lowres'] 34 | 35 | if overwrite_training_output_dir is not None: 36 | tr_dir = overwrite_training_output_dir 37 | else: 38 | tr_dir = network_training_output_dir 39 | 40 | current = join(tr_dir, model) 41 | if task is not None: 42 | current = join(current, task) 43 | if trainer is not None and plans is not None: 44 | current = join(current, trainer + "__" + plans) 45 | if fold is not None: 46 | current = join(current, "fold_%d" % fold) 47 | return current 48 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/nd_softmax.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import torch 16 | from torch import nn 17 | import torch.nn.functional as F 18 | 19 | 20 | softmax_helper = lambda x: F.softmax(x, 1) 21 | sigmoid_helper = lambda x: F.sigmoid(x) 22 | 23 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/one_hot_encoding.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | 17 | 18 | def to_one_hot(seg, all_seg_labels=None): 19 | if all_seg_labels is None: 20 | all_seg_labels = np.unique(seg) 21 | result = np.zeros((len(all_seg_labels), *seg.shape), dtype=seg.dtype) 22 | for i, l in enumerate(all_seg_labels): 23 | result[i][seg == l] = 1 24 | return result 25 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/random_stuff.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | class no_op(object): 17 | def __enter__(self): 18 | pass 19 | 20 | def __exit__(self, *args): 21 | pass 22 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/recursive_delete_npz.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from batchgenerators.utilities.file_and_folder_operations import * 17 | import argparse 18 | import os 19 | 20 | 21 | def recursive_delete_npz(current_directory: str): 22 | npz_files = subfiles(current_directory, join=True, suffix=".npz") 23 | npz_files = [i for i in npz_files if not i.endswith("segFromPrevStage.npz")] # to be extra safe 24 | _ = [os.remove(i) for i in npz_files] 25 | for d in subdirs(current_directory, join=False): 26 | if d != "pred_next_stage": 27 | recursive_delete_npz(join(current_directory, d)) 28 | 29 | 30 | if __name__ == "__main__": 31 | parser = argparse.ArgumentParser(usage="USE THIS RESPONSIBLY! DANGEROUS! I (Fabian) use this to remove npz files " 32 | "after I ran figure_out_what_to_submit") 33 | parser.add_argument("-f", help="folder", required=True) 34 | 35 | args = parser.parse_args() 36 | 37 | recursive_delete_npz(args.f) 38 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/recursive_rename_taskXX_to_taskXXX.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from batchgenerators.utilities.file_and_folder_operations import * 17 | import os 18 | 19 | 20 | def recursive_rename(folder): 21 | s = subdirs(folder, join=False) 22 | for ss in s: 23 | if ss.startswith("Task") and ss.find("_") == 6: 24 | task_id = int(ss[4:6]) 25 | name = ss[7:] 26 | os.rename(join(folder, ss), join(folder, "Task%03.0d_" % task_id + name)) 27 | s = subdirs(folder, join=True) 28 | for ss in s: 29 | recursive_rename(ss) 30 | 31 | if __name__ == "__main__": 32 | recursive_rename("/media/fabian/Results/nnFormer") 33 | recursive_rename("/media/fabian/nnformer") 34 | recursive_rename("/media/fabian/My Book/MedicalDecathlon") 35 | recursive_rename("/home/fabian/drives/datasets/nnFormer_raw") 36 | recursive_rename("/home/fabian/drives/datasets/nnFormer_preprocessed") 37 | recursive_rename("/home/fabian/drives/datasets/nnFormer_testSets") 38 | recursive_rename("/home/fabian/drives/datasets/results/nnFormer") 39 | recursive_rename("/home/fabian/drives/e230-dgx2-1-data_fabian/Decathlon_raw") 40 | recursive_rename("/home/fabian/drives/e230-dgx2-1-data_fabian/nnFormer_preprocessed") 41 | 42 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/sitk_stuff.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | import SimpleITK as sitk 17 | 18 | 19 | def copy_geometry(image: sitk.Image, ref: sitk.Image): 20 | image.SetOrigin(ref.GetOrigin()) 21 | image.SetDirection(ref.GetDirection()) 22 | image.SetSpacing(ref.GetSpacing()) 23 | return image 24 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/task_name_id_conversion.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | 16 | from nnformer.paths import nnFormer_raw_data, preprocessing_output_dir, nnFormer_cropped_data, network_training_output_dir 17 | from batchgenerators.utilities.file_and_folder_operations import * 18 | import numpy as np 19 | 20 | 21 | def convert_id_to_task_name(task_id: int): 22 | startswith = "Task%03.0d" % task_id 23 | if preprocessing_output_dir is not None: 24 | candidates_preprocessed = subdirs(preprocessing_output_dir, prefix=startswith, join=False) 25 | else: 26 | candidates_preprocessed = [] 27 | 28 | if nnFormer_raw_data is not None: 29 | candidates_raw = subdirs(nnFormer_raw_data, prefix=startswith, join=False) 30 | else: 31 | candidates_raw = [] 32 | 33 | if nnFormer_cropped_data is not None: 34 | candidates_cropped = subdirs(nnFormer_cropped_data, prefix=startswith, join=False) 35 | else: 36 | candidates_cropped = [] 37 | 38 | candidates_trained_models = [] 39 | if network_training_output_dir is not None: 40 | for m in ['2d', '3d_lowres', '3d_fullres', '3d_cascade_fullres']: 41 | if isdir(join(network_training_output_dir, m)): 42 | candidates_trained_models += subdirs(join(network_training_output_dir, m), prefix=startswith, join=False) 43 | 44 | all_candidates = candidates_cropped + candidates_preprocessed + candidates_raw + candidates_trained_models 45 | unique_candidates = np.unique(all_candidates) 46 | if len(unique_candidates) > 1: 47 | raise RuntimeError("More than one task name found for task id %d. Please correct that. (I looked in the " 48 | "following folders:\n%s\n%s\n%s" % (task_id, nnFormer_raw_data, preprocessing_output_dir, 49 | nnFormer_cropped_data)) 50 | if len(unique_candidates) == 0: 51 | raise RuntimeError("Could not find a task with the ID %d. Make sure the requested task ID exists and that " 52 | "nnU-Net knows where raw and preprocessed data are located (see Documentation - " 53 | "Installation). Here are your currently defined folders:\nnnFormer_preprocessed=%s\nRESULTS_" 54 | "FOLDER=%s\nnnFormer_raw_data_base=%s\nIf something is not right, adapt your environemnt " 55 | "variables." % 56 | (task_id, 57 | os.environ.get('nnFormer_preprocessed') if os.environ.get('nnFormer_preprocessed') is not None else 'None', 58 | os.environ.get('RESULTS_FOLDER') if os.environ.get('RESULTS_FOLDER') is not None else 'None', 59 | os.environ.get('nnFormer_raw_data_base') if os.environ.get('nnFormer_raw_data_base') is not None else 'None', 60 | )) 61 | return unique_candidates[0] 62 | 63 | 64 | def convert_task_name_to_id(task_name: str): 65 | assert task_name.startswith("Task") 66 | task_id = int(task_name[4:7]) 67 | return task_id 68 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/tensor_utilities.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import numpy as np 16 | import torch 17 | from torch import nn 18 | 19 | 20 | def sum_tensor(inp, axes, keepdim=False): 21 | axes = np.unique(axes).astype(int) 22 | if keepdim: 23 | for ax in axes: 24 | inp = inp.sum(int(ax), keepdim=True) 25 | else: 26 | for ax in sorted(axes, reverse=True): 27 | inp = inp.sum(int(ax)) 28 | return inp 29 | 30 | 31 | def mean_tensor(inp, axes, keepdim=False): 32 | axes = np.unique(axes).astype(int) 33 | if keepdim: 34 | for ax in axes: 35 | inp = inp.mean(int(ax), keepdim=True) 36 | else: 37 | for ax in sorted(axes, reverse=True): 38 | inp = inp.mean(int(ax)) 39 | return inp 40 | 41 | 42 | def flip(x, dim): 43 | """ 44 | flips the tensor at dimension dim (mirroring!) 45 | :param x: 46 | :param dim: 47 | :return: 48 | """ 49 | indices = [slice(None)] * x.dim() 50 | indices[dim] = torch.arange(x.size(dim) - 1, -1, -1, 51 | dtype=torch.long, device=x.device) 52 | return x[tuple(indices)] 53 | 54 | 55 | -------------------------------------------------------------------------------- /ASA_Segmentation/utilities/to_torch.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | import torch 16 | 17 | 18 | def maybe_to_torch(d): 19 | if isinstance(d, list): 20 | d = [maybe_to_torch(i) if not isinstance(i, torch.Tensor) else i for i in d] 21 | elif not isinstance(d, torch.Tensor): 22 | d = torch.from_numpy(d).float() 23 | return d 24 | 25 | 26 | def to_cuda(data, non_blocking=True, gpu_id=0): 27 | if isinstance(data, list): 28 | data = [i.cuda(gpu_id, non_blocking=non_blocking) for i in data] 29 | else: 30 | data = data.cuda(gpu_id, non_blocking=non_blocking) 31 | return data 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 LL3RD 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Attentive Symmetric Autoencoder for Brain MRI Segmentation-MICCAI 2022 2 | 3 | --- 4 | 5 | ## Getting Started 6 | This repo contains the supported code of Attentive Symmetric Autoencoder. It is based on [nnFormer](https://github.com/282857341/nnFormer). 7 | ### Installatioin 8 | We test our code in `CUDA 10.2` and `pytorch 1.8.1` 9 | 10 | ```bash 11 | git clone 12 | cd ASA_Pretrain 13 | pip install -r requirements.txt 14 | cd ../ASA_Segmentation 15 | pip install -e . 16 | ``` 17 | 18 | 19 | 20 | ### Pre-training ASA 21 | ```bash 22 | python3 -m torch.distributed.launch --nproc_per_node=2 --master_port 20003 tools/train.py --data_path DATA_PATH --output_dir OUTPUT_DIR 23 | ``` 24 | 25 | ### Segmentation 26 | #### Prepare Data 27 | First Create Folder for raw data, preprocessed data and result folder 28 | 29 | ```bash 30 | mkdir RAW_DATA_PATH 31 | mkdir PREPROCESSED_DATA_PATH 32 | mkdir RESULT_FOLDER_PATH 33 | 34 | export nnFormer_raw_data_base=RAW_DATA_PATH 35 | export nnFormer_preprocessed=PREPROCESSED_DATA_PATH 36 | export RESULTS_FOLDER_nnFormer=RESULT_FOLDER_PATH 37 | ``` 38 | 39 | Download the BraTS Dataset from the [Challenge](http://braintumorsegmentation.org/). 40 | 41 | Then change the dataset path in `dataset_conversion/Task999_BraTS_2021.py` and run it to convert the dataset. 42 | 43 | ```bash 44 | python dataset_conversion\Task999_BraTS_2021.py 45 | ``` 46 | 47 | After that, you can preprocess the above data using following commands: 48 | 49 | ```bash 50 | nnFormer_plan_and_preprocess -t 999 --verify_dataset_integrity 51 | ``` 52 | 53 | ### Training and Testing 54 | Download the [ASA_PRETRAIN_MODEL](https://drive.google.com/file/d/1oX6HYhxyVmltutjAmhyzTUl5aT526CQy/view?usp=sharing) and change the `PRETRAIN_PATH` in `training\network_training\nnFormerTrainerV2_MEDIUMVIT_MAE.py` 55 | 56 | 57 | 58 | Then Finetuning the model 59 | 60 | ```bash 61 | nnFormer_train --network 3d_fullres --network_trainer nnFormerTrainerV2_MEDIUMVIT --task 999 --fold 0 --tag DEFAULT 62 | ``` 63 | 64 | Testing 65 | 66 | ```bash 67 | nnFormer_predict -i "DATA_RAW_PATH/nnFormer_raw_data/Task999_BraTS2021/imagesTs/" -o "OUTPUT_PATH" -t 999 --tag "DEBUG" -tr nnFormerTrainerV2_MEDIUMVIT_MAE 68 | ``` 69 | 70 | ### Pretrain Model & Segmentation Model 71 | | Model | config | Params | 72 | | :-------: | :----------------------------------------------------------: | :----------------------------------------------------------: | 73 | | ASA_PRETRAIN | [config](https://drive.google.com/file/d/1JTlocHD02UrqedwOFgdkdbySis3xUI0T/view?usp=sharing) | [google drive](https://drive.google.com/file/d/1oX6HYhxyVmltutjAmhyzTUl5aT526CQy/view?usp=sharing) | 74 | | ASA_SEGMENTATION | [config](https://drive.google.com/file/d/133aL_-jpNndLHKvgmC9hwskuvMzz9RXX/view?usp=sharing) | [google drive](https://drive.google.com/file/d/12_0PahqUCZFtLMZLHnftv7FZkoDxYBOI/view?usp=sharing) | 75 | --------------------------------------------------------------------------------