|
| 1 | +import torch |
| 2 | +import numpy as np |
| 3 | +import pandas as pd |
| 4 | +import nibabel as nib |
| 5 | +import torch.nn.functional as F |
| 6 | +from tqdm import tqdm |
| 7 | +from pathlib import Path |
| 8 | +from niftiai import TensorImage3d |
| 9 | +from src.utils import ALIGN, create_grid, gauss_smoothing, LinearElasticity |
| 10 | +TEMPLATE_SIZE = (168, 204, 168) |
| 11 | +TEMPLATE_SHAPE = (113, 137, 113) |
| 12 | +TEMPLATE_ORIGIN = (72, 120, 84) |
| 13 | +data_path = 'data' |
| 14 | + |
| 15 | + |
| 16 | +def compose_affine(translation, rotation, zoom, shear): |
| 17 | + affine = torch.eye(4, device=translation.device) |
| 18 | + ZS = torch.diag(zoom) |
| 19 | + ZS[0, -2:] = shear[:2] |
| 20 | + ZS[1, 2] = shear[2] |
| 21 | + affine[:3, :3] = torch.mm(rotation, ZS) |
| 22 | + affine[:3, 3] = translation |
| 23 | + return affine |
| 24 | + |
| 25 | + |
| 26 | +def fill_nans(iy_disp, grid, nans): |
| 27 | + iy_disp_org = iy_disp.clone() |
| 28 | + nans_in_template = F.grid_sample(nans[None, None].float(), grid, align_corners=ALIGN)[0, 0] |
| 29 | + nans_in_template = nans_in_template > .0001 |
| 30 | + empty_mask = (grid[0, ..., 0].abs() > 1) + (grid[0, ..., 1].abs() > 1) + (grid[0, ..., 2].abs() > 1) > 0 |
| 31 | + nan_mask = nans_in_template | empty_mask |
| 32 | + elast = LinearElasticity() |
| 33 | + fill = torch.nn.Parameter(torch.zeros(int(nan_mask.sum()), 3, device=iy_disp.device, requires_grad=ALIGN)) |
| 34 | + opt = torch.optim.Adam([fill], lr=1e-3) |
| 35 | + for i in range(100): |
| 36 | + opt.zero_grad() |
| 37 | + iy_disp[nan_mask] = fill |
| 38 | + loss = elast(iy_disp[None]) |
| 39 | + loss.backward(retain_graph=True) |
| 40 | + opt.step() |
| 41 | + iy_disp = iy_disp.detach() |
| 42 | + iy_disp = gauss_smoothing(iy_disp.permute(3, 0, 1, 2)[None])[0].permute(1, 2, 3, 0) |
| 43 | + iy_disp_org[nan_mask] = iy_disp[nan_mask] |
| 44 | + return iy_disp_org |
| 45 | + |
| 46 | + |
| 47 | +def decompose_iy(iy, mask, nans): |
| 48 | + iy = (iy + torch.tensor(TEMPLATE_ORIGIN, device=iy.device)) / torch.tensor(TEMPLATE_SIZE, device=iy.device) |
| 49 | + iy = (iy * 2) - 1 |
| 50 | + translation = torch.nn.Parameter(torch.zeros(3).cuda(), requires_grad=True) |
| 51 | + rotation = torch.nn.Parameter(torch.eye(3).cuda(), requires_grad=True) |
| 52 | + zoom = torch.nn.Parameter(torch.ones(3).cuda(), requires_grad=True) |
| 53 | + shear = torch.nn.Parameter(torch.zeros(3).cuda(), requires_grad=True) |
| 54 | + opt = torch.optim.Adam([translation, rotation, zoom, shear], lr=3e-2) |
| 55 | + pbar = tqdm(range(100), disable=True) |
| 56 | + for _ in pbar: |
| 57 | + opt.zero_grad() |
| 58 | + affine = compose_affine(translation, rotation, zoom, shear) |
| 59 | + affine_grid = F.affine_grid(affine[None, :3], [1, 3, *iy.shape[:3]], align_corners=ALIGN) |
| 60 | + loss = ((iy[None, mask, :] - affine_grid[:, mask, :]) ** 2).mean() |
| 61 | + pbar.set_description(f'{loss.item()}') |
| 62 | + loss.backward() |
| 63 | + opt.step() |
| 64 | + iy_disp = iy.detach() - affine_grid.detach()[0] |
| 65 | + inv_affine = torch.linalg.inv(affine.detach()) |
| 66 | + inv_affine_grid = F.affine_grid(inv_affine[None, :3], [1, 3, *TEMPLATE_SHAPE], align_corners=ALIGN) |
| 67 | + iy_disp = iy_disp.permute(3, 0, 1, 2)[None] |
| 68 | + iy_disp_in_template_space = F.grid_sample(iy_disp, inv_affine_grid, align_corners=ALIGN)[0].permute(1, 2, 3, 0) |
| 69 | + iy_disp_in_template_space = fill_nans(iy_disp_in_template_space, inv_affine_grid, nans) |
| 70 | + return iy_disp_in_template_space.detach(), affine |
| 71 | + |
| 72 | + |
| 73 | +def mse(x, y): |
| 74 | + return ((x - y) ** 2).mean() |
| 75 | + |
| 76 | + |
| 77 | +class SyN: |
| 78 | + def __init__(self, time_steps=7, factor_diffeo=.1, sim_func=mse, mu=2., lam=1., optimizer=torch.optim.Adam): |
| 79 | + self.time_steps = time_steps |
| 80 | + self.factor_diffeo = factor_diffeo |
| 81 | + self.sim_func = sim_func |
| 82 | + self.reg_func = LinearElasticity(mu, lam, refresh_id_grid=True) |
| 83 | + self.optimizer = optimizer |
| 84 | + self.grid = None |
| 85 | + |
| 86 | + def fit_xy(self, targ_f_yx, iterations, learning_rate): |
| 87 | + x = 0 * targ_f_yx[:, :1] |
| 88 | + y = 0 * targ_f_yx[:, :1] |
| 89 | + self.grid = create_grid(x.shape[2:], x.device, dtype=x.dtype) |
| 90 | + v_xy = torch.zeros((x.shape[0], 3, *x.shape[2:]), device=x.device, dtype=x.dtype) |
| 91 | + v_yx = torch.zeros((x.shape[0], 3, *x.shape[2:]), device=x.device, dtype=x.dtype) |
| 92 | + v_xy = torch.nn.Parameter(v_xy, requires_grad=True) |
| 93 | + v_yx = torch.nn.Parameter(v_yx, requires_grad=True) |
| 94 | + optimizer = self.optimizer([v_xy, v_yx], learning_rate) |
| 95 | + for i in range(iterations): |
| 96 | + optimizer.zero_grad() |
| 97 | + images, flows = self.apply_flows(x, y, v_xy, v_yx) |
| 98 | + loss = self.sim_func(targ_f_yx, flows['yx_full']) |
| 99 | + loss.backward() |
| 100 | + optimizer.step() |
| 101 | + return flows['xy_full'].detach(), v_xy, v_yx, loss.detach().item() |
| 102 | + |
| 103 | + def apply_flows(self, x, y, v_xy, v_yx): |
| 104 | + half_flows = self.diffeomorphic_transform(torch.cat([v_xy, v_yx, -v_xy, -v_yx])) |
| 105 | + half_images = self.spatial_transform(torch.cat([x, y]), half_flows[:2]) |
| 106 | + full_flows = self.composition_transform(half_flows[:2], half_flows[2:].flip(0)) |
| 107 | + full_images = self.spatial_transform(torch.cat([x, y]), full_flows) |
| 108 | + images = {'xy_half': half_images[:1], 'yx_half': half_images[1:2], |
| 109 | + 'xy_full': full_images[:1], 'yx_full': full_images[1:2]} |
| 110 | + flows = {'xy_half': half_flows[:1], 'yx_half': half_flows[1:2], |
| 111 | + 'xy_full': full_flows[:1], 'yx_full': full_flows[1:2]} |
| 112 | + return images, flows |
| 113 | + |
| 114 | + def diffeomorphic_transform(self, flow): |
| 115 | + flow = self.factor_diffeo * flow / (2 ** self.time_steps) |
| 116 | + for i in range(self.time_steps): |
| 117 | + flow = flow + self.spatial_transform(flow, flow) |
| 118 | + return flow |
| 119 | + |
| 120 | + def composition_transform(self, flow_1, flow_2): |
| 121 | + return flow_2 + self.spatial_transform(flow_1, flow_2) |
| 122 | + |
| 123 | + def spatial_transform(self, x, flow): |
| 124 | + return F.grid_sample(x.type(torch.float32), self.grid.type(torch.float32) + flow.permute(0, 2, 3, 4, 1), |
| 125 | + align_corners=ALIGN, padding_mode='border') |
| 126 | + |
| 127 | + |
| 128 | +def preprocess_cat12_registration(p0_filepaths, iy_filepaths, y_filepaths, dest_dir=None): |
| 129 | + nib_affine = np.array([[-1.5,0,0,84], [0,1.5,0,-120], [0,0,1.5,-72], [0,0,0,0]]) |
| 130 | + for p0_fpath, iy_fpath, y_fpath in tqdm(zip(p0_filepaths, iy_filepaths, y_filepaths), total=len(y_filepaths)): |
| 131 | + p0 = TensorImage3d.create(p0_fpath)[0].cuda() |
| 132 | + iy = nib.load(iy_fpath) |
| 133 | + iy = TensorImage3d.create(iy.get_fdata(), affine=iy.affine, header=iy.header).cuda() |
| 134 | + y = nib.load(y_fpath) |
| 135 | + y = TensorImage3d.create(y.get_fdata(), affine=y.affine, header=y.header).cuda() |
| 136 | + y, iy = y[..., 0, :].flip(3), iy[..., 0, :].flip(3) |
| 137 | + brainmask = p0 > .001 |
| 138 | + nans = torch.isnan(iy[..., 0]) |
| 139 | + iy[nans, :] = 0 |
| 140 | + mask = (~brainmask & ~nans) |
| 141 | + iy_disp, affine = decompose_iy(iy, mask, nans) |
| 142 | + iy_disp = iy_disp.permute(3, 0, 1, 2) |
| 143 | + syn = SyN() |
| 144 | + y_disp, v_xy, v_yx, lss = syn.fit_xy(iy_disp[None], iterations=100, learning_rate=1e-1) |
| 145 | + if dest_dir is not None: |
| 146 | + filename = p0_fpath.split('/')[-1].split('.')[0][2:] |
| 147 | + pd.DataFrame(affine).to_csv(f'{dest_dir}/affine/{filename}.csv', index=False) |
| 148 | + TensorImage3d(iy_disp, affine=nib_affine, header=iy.header).save(f'{dest_dir}/flow_yx/{filename}.nii.gz') |
| 149 | + TensorImage3d(y_disp[0], affine=nib_affine, header=iy.header).save(f'{dest_dir}/flow_xy/{filename}.nii.gz') |
| 150 | + TensorImage3d(v_yx[0], affine=nib_affine, header=iy.header).save(f'{dest_dir}/v_yx/{filename}.nii.gz') |
| 151 | + TensorImage3d(v_xy[0], affine=nib_affine, header=iy.header).save(f'{dest_dir}/v_xy/{filename}.nii.gz') |
| 152 | + |
| 153 | + |
| 154 | +if __name__ == '__main__': |
| 155 | + df = pd.read_csv(f'{data_path}/csvs/openneuro_hd.csv') |
| 156 | + cat_dir = f'{data_path}/t1/CAT12.8.2' |
| 157 | + p0_fps = cat_dir + '/mri/p0' + df.filename + '.nii' |
| 158 | + iy_fps = cat_dir + '/mri/iy_' + df.filename + '.nii' |
| 159 | + y_fps = cat_dir + '/mri/y_' + df.filename + '.nii' |
| 160 | + for subdir in ['affine', 'flow_xy', 'flow_yx', 'v_xy', 'v_yx']: Path(f'{data_path}/{subdir}').mkdir(exist_ok=True) |
| 161 | + preprocess_cat12_registration(p0_fps, iy_fps, y_fps, dest_dir=data_path) |
0 commit comments