-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfireants_oasis.py
162 lines (151 loc) · 6.89 KB
/
fireants_oasis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
from glob import glob
import time
import numpy as np
import torch
import SimpleITK as sitk
sitk.ProcessObject_SetGlobalWarningDisplay(False)
from fireants.io.image import Image, BatchedImages
from fireants.registration.affine import AffineRegistration
from fireants.registration.greedy import GreedyRegistration
from fireants.registration.syn import SyNRegistration
import argparse
from tqdm import tqdm
import pickle
import itertools
from torch.nn import functional as F
from ray import tune, air
import os.path as osp
import ray
from fireants.scripts.evalutils import compute_metrics
ROOT_DIR = "/data/neurite-OASIS"
def dice_score(p, q):
''' computes the dice score between two tensors '''
return 2.0 * (p * q).mean() / (p.mean() + q.mean())
def register_val_dataset(config, test=False):
''' given a configuration, register the images to each other determined by the random seed,
and compute the overall dice score
'''
rng = np.random.RandomState(config['seed'])
images = sorted(glob(osp.join(ROOT_DIR, 'OASIS*', 'aligned_norm.nii.gz')))
labels = sorted(glob(osp.join(ROOT_DIR, 'OASIS*', 'aligned_seg35.nii.gz')))
assert len(images) == len(labels)
results_dict = {}
# tune
## pairs are (fixed, moving)
pairs = [(x, x+1) for x in range(len(images)-1)]
if not test or True:
# pairs = pairs[-49:]
pairs = [126, 101, 91, 334, 90] #[::-1]
pairs = [(x, x+1) for x in pairs]
print("Using #pairs: ", len(pairs))
config['cc_size'] = int(np.around(config['cc_size']))
# for each pair, register the images
dices_all = []
for fixed_id, moving_id in pairs[::-1]:
fixed_image, moving_image = Image.load_file(images[fixed_id]), Image.load_file(images[moving_id])
fixed_image, moving_image = BatchedImages(fixed_image), BatchedImages(moving_image)
# register
if config['algo'] == 'greedy':
deformable = GreedyRegistration([4, 2, 1], [250, 200, 100],
fixed_image, moving_image, deformation_type='compositive',
optimizer='adam', optimizer_lr=config['lr'], cc_kernel_size=1 + 2*config['cc_size'], # 2k + 1
optimizer_params={'beta1': 0.1, 'scaledown': False},
# max_tolerance_iters=10,
smooth_grad_sigma=config['grad_sigma'],
smooth_warp_sigma=config['warp_sigma'])
elif config['algo'] == 'syn':
deformable = SyNRegistration([4, 2, 1], [200, 100, 50],
fixed_image, moving_image, deformation_type='compositive',
optimizer='adam', optimizer_lr=config['lr'], cc_kernel_size=1 + 2*config['cc_size'], # 2k + 1
smooth_grad_sigma=config['grad_sigma'],
smooth_warp_sigma=config['warp_sigma'])
else:
raise NotImplementedError
# deformation
deformable.optimize(save_transformed=False)
warp = deformable.get_warped_coordinates(fixed_image, moving_image)
# del deformable
# evaluate
fixed_seg, moving_seg = Image.load_file(labels[fixed_id]), Image.load_file(labels[moving_id])
fixed_data, moving_data = fixed_seg.array, moving_seg.array
# size is [1, 1, H, W, D]
fixed_data = F.one_hot(fixed_data[0].long(), num_classes=36).permute(0, 4, 1, 2, 3).float()[:, 1:]
moving_data = F.one_hot(moving_data[0].long(), num_classes=36).permute(0, 4, 1, 2, 3).float()[:, 1:]
moved_data = F.grid_sample(moving_data, warp, mode='bilinear', align_corners=True)
print(fixed_data.shape, moving_data.shape, moved_data.shape)
# get names
fidname, midname = images[fixed_id].split("/")[-2], images[moving_id].split("/")[-2]
ret = compute_metrics(moved_data, fixed_data, warp, method='fireants')
results_dict[(fidname, midname)] = ret
if not test:
dices_all.append(ret['dice'])
for k, v in ret.items():
print(k, np.mean(v))
# compute the overall dice score
if not test:
tune.report(dice=np.mean(dices_all))
else:
with open(f"oasis_{config['algo']}_results.pkl", 'wb') as f:
pickle.dump(results_dict, f)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--root_dir', type=str, default="/data/OASIS/")
parser.add_argument('--rng_seed', type=int, default=86781) # random scribble
parser.add_argument('--mode', type=str, required=True, choices=['tune', 'test'])
parser.add_argument('--algo', type=str, required=True, choices=['greedy', 'syn'])
parser.add_argument('--num_val', type=int, default=50) # number of validation cases
parser.add_argument('--num_samples', type=int, default=1000) # number of validation cases
args = parser.parse_args()
# what configs to run
if args.mode == 'tune':
rem_configs = args.num_samples / 40
s = int(np.sqrt(rem_configs))
small_fac, large_fac = int(s/np.sqrt(2)), int(s * np.sqrt(2))
config = {
'seed': args.rng_seed,
'num_val': args.num_val,
'algo': args.algo,
'lr': tune.grid_search(np.arange(0.1, 1.1, 10)), # 10
'grad_sigma': tune.grid_search(np.arange(0, 3, large_fac)),
'warp_sigma': tune.grid_search(np.arange(0, 3, small_fac)),
'cc_size': tune.grid_search([1, 2, 3, 4]), # 4
}
# set algo
from ray.tune.search.bayesopt import BayesOptSearch
ray.init()
scheduler = ray.tune.schedulers.FIFOScheduler()
tuner = tune.Tuner(
tune.with_resources(register_val_dataset, resources={'cpu': 0.5, 'gpu': 0.25}),
tune_config=tune.TuneConfig(
metric='dice',
mode='max',
num_samples=1,
scheduler=scheduler,
),
run_config=air.RunConfig(name="oasis_{}_{}samples".format(args.algo, args.num_samples)),
param_space=config,
)
results = tuner.fit()
ray.shutdown()
elif args.mode == 'test':
if args.algo == 'greedy':
config = {
'seed': args.rng_seed,
'num_val': args.num_val,
'algo': args.algo,
'lr': 0.25,
'grad_sigma': 1,
'warp_sigma': 0.25,
'cc_size': 3,
}
else:
config = {
'seed': args.rng_seed,
'num_val': args.num_val,
'algo': args.algo,
'lr': 0.1,
'grad_sigma': 0.5,
'warp_sigma': 0.25,
'cc_size': 2,
}
register_val_dataset(config, test=True)