qicq1c commited on
Commit
0824aaf
1 Parent(s): 36e3ab3

173d1be0e72b3b98aa37c8c8529875e4b3f0277a58df6eabd36c541c2f90d0dd

Browse files
Files changed (18) hide show
  1. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/ldm/vq_gan_3d/model/lpips.py +181 -0
  2. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/ldm/vq_gan_3d/model/vqgan.py +561 -0
  3. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/ldm/vq_gan_3d/utils.py +177 -0
  4. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_kidney_fold0_early.pt +3 -0
  5. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_kidney_fold0_noearly_t200.pt +3 -0
  6. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_liver_fold0_early.pt +3 -0
  7. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_liver_fold0_noearly_t200.pt +3 -0
  8. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_pancreas_fold0_early.pt +3 -0
  9. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_pancreas_fold0_noearly_t200.pt +3 -0
  10. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/recon_96d4_all.ckpt +3 -0
  11. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/utils.py +465 -0
  12. Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/utils_.py +298 -0
  13. Generation_Pipeline_filter_all2/syn_pancreas/healthy_pancreas_1k.txt +774 -0
  14. Generation_Pipeline_filter_all2/syn_pancreas/requirements.txt +94 -0
  15. Generation_Pipeline_filter_all2/val_set/bodymap_colon.txt +25 -0
  16. Generation_Pipeline_filter_all2/val_set/bodymap_kidney.txt +24 -0
  17. Generation_Pipeline_filter_all2/val_set/bodymap_liver.txt +25 -0
  18. Generation_Pipeline_filter_all2/val_set/bodymap_pancreas.txt +24 -0
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/ldm/vq_gan_3d/model/lpips.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adapted from https://github.com/SongweiGe/TATS"""
2
+
3
+ """Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models"""
4
+
5
+
6
+ from collections import namedtuple
7
+ from torchvision import models
8
+ import torch.nn as nn
9
+ import torch
10
+ from tqdm import tqdm
11
+ import requests
12
+ import os
13
+ import hashlib
14
+ URL_MAP = {
15
+ "vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"
16
+ }
17
+
18
+ CKPT_MAP = {
19
+ "vgg_lpips": "vgg.pth"
20
+ }
21
+
22
+ MD5_MAP = {
23
+ "vgg_lpips": "d507d7349b931f0638a25a48a722f98a"
24
+ }
25
+
26
+
27
+ def download(url, local_path, chunk_size=1024):
28
+ os.makedirs(os.path.split(local_path)[0], exist_ok=True)
29
+ with requests.get(url, stream=True) as r:
30
+ total_size = int(r.headers.get("content-length", 0))
31
+ with tqdm(total=total_size, unit="B", unit_scale=True) as pbar:
32
+ with open(local_path, "wb") as f:
33
+ for data in r.iter_content(chunk_size=chunk_size):
34
+ if data:
35
+ f.write(data)
36
+ pbar.update(chunk_size)
37
+
38
+
39
+ def md5_hash(path):
40
+ with open(path, "rb") as f:
41
+ content = f.read()
42
+ return hashlib.md5(content).hexdigest()
43
+
44
+
45
+ def get_ckpt_path(name, root, check=False):
46
+ assert name in URL_MAP
47
+ path = os.path.join(root, CKPT_MAP[name])
48
+ if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]):
49
+ print("Downloading {} model from {} to {}".format(
50
+ name, URL_MAP[name], path))
51
+ download(URL_MAP[name], path)
52
+ md5 = md5_hash(path)
53
+ assert md5 == MD5_MAP[name], md5
54
+ return path
55
+
56
+
57
+ class LPIPS(nn.Module):
58
+ # Learned perceptual metric
59
+ def __init__(self, use_dropout=True):
60
+ super().__init__()
61
+ self.scaling_layer = ScalingLayer()
62
+ self.chns = [64, 128, 256, 512, 512] # vg16 features
63
+ self.net = vgg16(pretrained=True, requires_grad=False)
64
+ self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)
65
+ self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)
66
+ self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)
67
+ self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)
68
+ self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)
69
+ # self.load_from_pretrained()
70
+ for param in self.parameters():
71
+ param.requires_grad = False
72
+
73
+ def load_from_pretrained(self, name="vgg_lpips"):
74
+ ckpt = get_ckpt_path(name, os.path.join(
75
+ os.path.dirname(os.path.abspath(__file__)), "cache"))
76
+ self.load_state_dict(torch.load(
77
+ ckpt, map_location=torch.device("cpu")), strict=False)
78
+ print("loaded pretrained LPIPS loss from {}".format(ckpt))
79
+
80
+ @classmethod
81
+ def from_pretrained(cls, name="vgg_lpips"):
82
+ if name is not "vgg_lpips":
83
+ raise NotImplementedError
84
+ model = cls()
85
+ ckpt = get_ckpt_path(name, os.path.join(
86
+ os.path.dirname(os.path.abspath(__file__)), "cache"))
87
+ model.load_state_dict(torch.load(
88
+ ckpt, map_location=torch.device("cpu")), strict=False)
89
+ return model
90
+
91
+ def forward(self, input, target):
92
+ in0_input, in1_input = (self.scaling_layer(
93
+ input), self.scaling_layer(target))
94
+ outs0, outs1 = self.net(in0_input), self.net(in1_input)
95
+ feats0, feats1, diffs = {}, {}, {}
96
+ lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4]
97
+ for kk in range(len(self.chns)):
98
+ feats0[kk], feats1[kk] = normalize_tensor(
99
+ outs0[kk]), normalize_tensor(outs1[kk])
100
+ diffs[kk] = (feats0[kk] - feats1[kk]) ** 2
101
+
102
+ res = [spatial_average(lins[kk].model(diffs[kk]), keepdim=True)
103
+ for kk in range(len(self.chns))]
104
+ val = res[0]
105
+ for l in range(1, len(self.chns)):
106
+ val += res[l]
107
+ return val
108
+
109
+
110
+ class ScalingLayer(nn.Module):
111
+ def __init__(self):
112
+ super(ScalingLayer, self).__init__()
113
+ self.register_buffer('shift', torch.Tensor(
114
+ [-.030, -.088, -.188])[None, :, None, None])
115
+ self.register_buffer('scale', torch.Tensor(
116
+ [.458, .448, .450])[None, :, None, None])
117
+
118
+ def forward(self, inp):
119
+ return (inp - self.shift) / self.scale
120
+
121
+
122
+ class NetLinLayer(nn.Module):
123
+ """ A single linear layer which does a 1x1 conv """
124
+
125
+ def __init__(self, chn_in, chn_out=1, use_dropout=False):
126
+ super(NetLinLayer, self).__init__()
127
+ layers = [nn.Dropout(), ] if (use_dropout) else []
128
+ layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1,
129
+ padding=0, bias=False), ]
130
+ self.model = nn.Sequential(*layers)
131
+
132
+
133
+ class vgg16(torch.nn.Module):
134
+ def __init__(self, requires_grad=False, pretrained=True):
135
+ super(vgg16, self).__init__()
136
+ vgg_pretrained_features = models.vgg16(pretrained=pretrained).features
137
+ self.slice1 = torch.nn.Sequential()
138
+ self.slice2 = torch.nn.Sequential()
139
+ self.slice3 = torch.nn.Sequential()
140
+ self.slice4 = torch.nn.Sequential()
141
+ self.slice5 = torch.nn.Sequential()
142
+ self.N_slices = 5
143
+ for x in range(4):
144
+ self.slice1.add_module(str(x), vgg_pretrained_features[x])
145
+ for x in range(4, 9):
146
+ self.slice2.add_module(str(x), vgg_pretrained_features[x])
147
+ for x in range(9, 16):
148
+ self.slice3.add_module(str(x), vgg_pretrained_features[x])
149
+ for x in range(16, 23):
150
+ self.slice4.add_module(str(x), vgg_pretrained_features[x])
151
+ for x in range(23, 30):
152
+ self.slice5.add_module(str(x), vgg_pretrained_features[x])
153
+ if not requires_grad:
154
+ for param in self.parameters():
155
+ param.requires_grad = False
156
+
157
+ def forward(self, X):
158
+ h = self.slice1(X)
159
+ h_relu1_2 = h
160
+ h = self.slice2(h)
161
+ h_relu2_2 = h
162
+ h = self.slice3(h)
163
+ h_relu3_3 = h
164
+ h = self.slice4(h)
165
+ h_relu4_3 = h
166
+ h = self.slice5(h)
167
+ h_relu5_3 = h
168
+ vgg_outputs = namedtuple(
169
+ "VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'])
170
+ out = vgg_outputs(h_relu1_2, h_relu2_2,
171
+ h_relu3_3, h_relu4_3, h_relu5_3)
172
+ return out
173
+
174
+
175
+ def normalize_tensor(x, eps=1e-10):
176
+ norm_factor = torch.sqrt(torch.sum(x**2, dim=1, keepdim=True))
177
+ return x/(norm_factor+eps)
178
+
179
+
180
+ def spatial_average(x, keepdim=True):
181
+ return x.mean([2, 3], keepdim=keepdim)
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/ldm/vq_gan_3d/model/vqgan.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Adapted from https://github.com/SongweiGe/TATS"""
2
+ # Copyright (c) Meta Platforms, Inc. All Rights Reserved
3
+
4
+ import math
5
+ import argparse
6
+ import numpy as np
7
+ import pickle as pkl
8
+
9
+ import pytorch_lightning as pl
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import torch.distributed as dist
14
+
15
+ from ..utils import shift_dim, adopt_weight, comp_getattr
16
+ from .lpips import LPIPS
17
+ from .codebook import Codebook
18
+
19
+
20
+ def silu(x):
21
+ return x*torch.sigmoid(x)
22
+
23
+
24
+ class SiLU(nn.Module):
25
+ def __init__(self):
26
+ super(SiLU, self).__init__()
27
+
28
+ def forward(self, x):
29
+ return silu(x)
30
+
31
+
32
+ def hinge_d_loss(logits_real, logits_fake):
33
+ loss_real = torch.mean(F.relu(1. - logits_real))
34
+ loss_fake = torch.mean(F.relu(1. + logits_fake))
35
+ d_loss = 0.5 * (loss_real + loss_fake)
36
+ return d_loss
37
+
38
+
39
+ def vanilla_d_loss(logits_real, logits_fake):
40
+ d_loss = 0.5 * (
41
+ torch.mean(torch.nn.functional.softplus(-logits_real)) +
42
+ torch.mean(torch.nn.functional.softplus(logits_fake)))
43
+ return d_loss
44
+
45
+
46
+ class VQGAN(pl.LightningModule):
47
+ def __init__(self, cfg):
48
+ super().__init__()
49
+ self.cfg = cfg
50
+ self.embedding_dim = cfg.model.embedding_dim # 8
51
+ self.n_codes = cfg.model.n_codes # 16384
52
+
53
+ self.encoder = Encoder(cfg.model.n_hiddens, # 16
54
+ cfg.model.downsample, # [2, 2, 2]
55
+ cfg.dataset.image_channels, # 1
56
+ cfg.model.norm_type, # group
57
+ cfg.model.padding_type, # replicate
58
+ cfg.model.num_groups, # 32
59
+ )
60
+ self.decoder = Decoder(
61
+ cfg.model.n_hiddens, cfg.model.downsample, cfg.dataset.image_channels, cfg.model.norm_type, cfg.model.num_groups)
62
+ self.enc_out_ch = self.encoder.out_channels
63
+ self.pre_vq_conv = SamePadConv3d(
64
+ self.enc_out_ch, cfg.model.embedding_dim, 1, padding_type=cfg.model.padding_type)
65
+ self.post_vq_conv = SamePadConv3d(
66
+ cfg.model.embedding_dim, self.enc_out_ch, 1)
67
+
68
+ self.codebook = Codebook(cfg.model.n_codes, cfg.model.embedding_dim,
69
+ no_random_restart=cfg.model.no_random_restart, restart_thres=cfg.model.restart_thres)
70
+
71
+ self.gan_feat_weight = cfg.model.gan_feat_weight
72
+ # TODO: Changed batchnorm from sync to normal
73
+ self.image_discriminator = NLayerDiscriminator(
74
+ cfg.dataset.image_channels, cfg.model.disc_channels, cfg.model.disc_layers, norm_layer=nn.BatchNorm2d)
75
+ self.video_discriminator = NLayerDiscriminator3D(
76
+ cfg.dataset.image_channels, cfg.model.disc_channels, cfg.model.disc_layers, norm_layer=nn.BatchNorm3d)
77
+
78
+ if cfg.model.disc_loss_type == 'vanilla':
79
+ self.disc_loss = vanilla_d_loss
80
+ elif cfg.model.disc_loss_type == 'hinge':
81
+ self.disc_loss = hinge_d_loss
82
+
83
+ self.perceptual_model = LPIPS().eval()
84
+
85
+ self.image_gan_weight = cfg.model.image_gan_weight
86
+ self.video_gan_weight = cfg.model.video_gan_weight
87
+
88
+ self.perceptual_weight = cfg.model.perceptual_weight
89
+
90
+ self.l1_weight = cfg.model.l1_weight
91
+ self.save_hyperparameters()
92
+
93
+ def encode(self, x, include_embeddings=False, quantize=True):
94
+ h = self.pre_vq_conv(self.encoder(x))
95
+ if quantize:
96
+ vq_output = self.codebook(h)
97
+ if include_embeddings:
98
+ return vq_output['embeddings'], vq_output['encodings']
99
+ else:
100
+ return vq_output['encodings']
101
+ return h
102
+
103
+ def decode(self, latent, quantize=False):
104
+ if quantize:
105
+ vq_output = self.codebook(latent)
106
+ latent = vq_output['encodings']
107
+ h = F.embedding(latent, self.codebook.embeddings)
108
+ h = self.post_vq_conv(shift_dim(h, -1, 1))
109
+ return self.decoder(h)
110
+
111
+ def forward(self, x, optimizer_idx=None, log_image=False):
112
+ B, C, T, H, W = x.shape
113
+ z = self.pre_vq_conv(self.encoder(x)) # [2, 32, 32, 32, 32] [2, 8, 32, 32, 32]
114
+ vq_output = self.codebook(z) # ['embeddings', 'encodings', 'commitment_loss', 'perplexity']
115
+ x_recon = self.decoder(self.post_vq_conv(vq_output['embeddings'])) # [2, 8, 32, 32, 32] [2, 32, 32, 32, 32]
116
+
117
+ recon_loss = F.l1_loss(x_recon, x) * self.l1_weight
118
+
119
+ # Selects one random 2D image from each 3D Image
120
+ frame_idx = torch.randint(0, T, [B]).cuda()
121
+ frame_idx_selected = frame_idx.reshape(-1,
122
+ 1, 1, 1, 1).repeat(1, C, 1, H, W) # [2, 1, 1, 64, 64]
123
+ frames = torch.gather(x, 2, frame_idx_selected).squeeze(2) # [2, 1, 64, 64]
124
+ frames_recon = torch.gather(x_recon, 2, frame_idx_selected).squeeze(2) # [2, 1, 64, 64]
125
+
126
+ if log_image:
127
+ return frames, frames_recon, x, x_recon
128
+
129
+ if optimizer_idx == 0:
130
+ # Autoencoder - train the "generator"
131
+
132
+ # Perceptual loss
133
+ perceptual_loss = 0
134
+ if self.perceptual_weight > 0:
135
+ perceptual_loss = self.perceptual_model(
136
+ frames, frames_recon).mean() * self.perceptual_weight
137
+
138
+ # Discriminator loss (turned on after a certain epoch)
139
+ logits_image_fake, pred_image_fake = self.image_discriminator(
140
+ frames_recon)
141
+ logits_video_fake, pred_video_fake = self.video_discriminator(
142
+ x_recon)
143
+ g_image_loss = -torch.mean(logits_image_fake)
144
+ g_video_loss = -torch.mean(logits_video_fake)
145
+ g_loss = self.image_gan_weight*g_image_loss + self.video_gan_weight*g_video_loss
146
+ disc_factor = adopt_weight(
147
+ self.global_step, threshold=self.cfg.model.discriminator_iter_start)
148
+ aeloss = disc_factor * g_loss
149
+
150
+ # GAN feature matching loss - tune features such that we get the same prediction result on the discriminator
151
+ image_gan_feat_loss = 0
152
+ video_gan_feat_loss = 0
153
+ feat_weights = 4.0 / (3 + 1)
154
+ if self.image_gan_weight > 0:
155
+ logits_image_real, pred_image_real = self.image_discriminator(
156
+ frames)
157
+ for i in range(len(pred_image_fake)-1):
158
+ image_gan_feat_loss += feat_weights * \
159
+ F.l1_loss(pred_image_fake[i], pred_image_real[i].detach(
160
+ )) * (self.image_gan_weight > 0)
161
+ if self.video_gan_weight > 0:
162
+ logits_video_real, pred_video_real = self.video_discriminator(
163
+ x)
164
+ for i in range(len(pred_video_fake)-1):
165
+ video_gan_feat_loss += feat_weights * \
166
+ F.l1_loss(pred_video_fake[i], pred_video_real[i].detach(
167
+ )) * (self.video_gan_weight > 0)
168
+ gan_feat_loss = disc_factor * self.gan_feat_weight * \
169
+ (image_gan_feat_loss + video_gan_feat_loss)
170
+
171
+ self.log("train/g_image_loss", g_image_loss,
172
+ logger=True, on_step=True, on_epoch=True)
173
+ self.log("train/g_video_loss", g_video_loss,
174
+ logger=True, on_step=True, on_epoch=True)
175
+ self.log("train/image_gan_feat_loss", image_gan_feat_loss,
176
+ logger=True, on_step=True, on_epoch=True)
177
+ self.log("train/video_gan_feat_loss", video_gan_feat_loss,
178
+ logger=True, on_step=True, on_epoch=True)
179
+ self.log("train/perceptual_loss", perceptual_loss,
180
+ prog_bar=True, logger=True, on_step=True, on_epoch=True)
181
+ self.log("train/recon_loss", recon_loss, prog_bar=True,
182
+ logger=True, on_step=True, on_epoch=True)
183
+ self.log("train/aeloss", aeloss, prog_bar=True,
184
+ logger=True, on_step=True, on_epoch=True)
185
+ self.log("train/commitment_loss", vq_output['commitment_loss'],
186
+ prog_bar=True, logger=True, on_step=True, on_epoch=True)
187
+ self.log('train/perplexity', vq_output['perplexity'],
188
+ prog_bar=True, logger=True, on_step=True, on_epoch=True)
189
+ return recon_loss, x_recon, vq_output, aeloss, perceptual_loss, gan_feat_loss
190
+
191
+ if optimizer_idx == 1:
192
+ # Train discriminator
193
+ logits_image_real, _ = self.image_discriminator(frames.detach())
194
+ logits_video_real, _ = self.video_discriminator(x.detach())
195
+
196
+ logits_image_fake, _ = self.image_discriminator(
197
+ frames_recon.detach())
198
+ logits_video_fake, _ = self.video_discriminator(x_recon.detach())
199
+
200
+ d_image_loss = self.disc_loss(logits_image_real, logits_image_fake)
201
+ d_video_loss = self.disc_loss(logits_video_real, logits_video_fake)
202
+ disc_factor = adopt_weight(
203
+ self.global_step, threshold=self.cfg.model.discriminator_iter_start)
204
+ discloss = disc_factor * \
205
+ (self.image_gan_weight*d_image_loss +
206
+ self.video_gan_weight*d_video_loss)
207
+
208
+ self.log("train/logits_image_real", logits_image_real.mean().detach(),
209
+ logger=True, on_step=True, on_epoch=True)
210
+ self.log("train/logits_image_fake", logits_image_fake.mean().detach(),
211
+ logger=True, on_step=True, on_epoch=True)
212
+ self.log("train/logits_video_real", logits_video_real.mean().detach(),
213
+ logger=True, on_step=True, on_epoch=True)
214
+ self.log("train/logits_video_fake", logits_video_fake.mean().detach(),
215
+ logger=True, on_step=True, on_epoch=True)
216
+ self.log("train/d_image_loss", d_image_loss,
217
+ logger=True, on_step=True, on_epoch=True)
218
+ self.log("train/d_video_loss", d_video_loss,
219
+ logger=True, on_step=True, on_epoch=True)
220
+ self.log("train/discloss", discloss, prog_bar=True,
221
+ logger=True, on_step=True, on_epoch=True)
222
+ return discloss
223
+
224
+ perceptual_loss = self.perceptual_model(
225
+ frames, frames_recon) * self.perceptual_weight
226
+ return recon_loss, x_recon, vq_output, perceptual_loss
227
+
228
+ def training_step(self, batch, batch_idx, optimizer_idx):
229
+ x = batch['image']
230
+ if optimizer_idx == 0:
231
+ recon_loss, _, vq_output, aeloss, perceptual_loss, gan_feat_loss = self.forward(
232
+ x, optimizer_idx)
233
+ commitment_loss = vq_output['commitment_loss']
234
+ loss = recon_loss + commitment_loss + aeloss + perceptual_loss + gan_feat_loss
235
+ if optimizer_idx == 1:
236
+ discloss = self.forward(x, optimizer_idx)
237
+ loss = discloss
238
+ return loss
239
+
240
+ def validation_step(self, batch, batch_idx):
241
+ x = batch['image'] # TODO: batch['stft']
242
+ recon_loss, _, vq_output, perceptual_loss = self.forward(x)
243
+ self.log('val/recon_loss', recon_loss, prog_bar=True)
244
+ self.log('val/perceptual_loss', perceptual_loss, prog_bar=True)
245
+ self.log('val/perplexity', vq_output['perplexity'], prog_bar=True)
246
+ self.log('val/commitment_loss',
247
+ vq_output['commitment_loss'], prog_bar=True)
248
+
249
+ def configure_optimizers(self):
250
+ lr = self.cfg.model.lr
251
+ opt_ae = torch.optim.Adam(list(self.encoder.parameters()) +
252
+ list(self.decoder.parameters()) +
253
+ list(self.pre_vq_conv.parameters()) +
254
+ list(self.post_vq_conv.parameters()) +
255
+ list(self.codebook.parameters()),
256
+ lr=lr, betas=(0.5, 0.9))
257
+ opt_disc = torch.optim.Adam(list(self.image_discriminator.parameters()) +
258
+ list(self.video_discriminator.parameters()),
259
+ lr=lr, betas=(0.5, 0.9))
260
+ return [opt_ae, opt_disc], []
261
+
262
+ def log_images(self, batch, **kwargs):
263
+ log = dict()
264
+ x = batch['image']
265
+ x = x.to(self.device)
266
+ frames, frames_rec, _, _ = self(x, log_image=True)
267
+ log["inputs"] = frames
268
+ log["reconstructions"] = frames_rec
269
+ #log['mean_org'] = batch['mean_org']
270
+ #log['std_org'] = batch['std_org']
271
+ return log
272
+
273
+ def log_videos(self, batch, **kwargs):
274
+ log = dict()
275
+ x = batch['image']
276
+ _, _, x, x_rec = self(x, log_image=True)
277
+ log["inputs"] = x
278
+ log["reconstructions"] = x_rec
279
+ #log['mean_org'] = batch['mean_org']
280
+ #log['std_org'] = batch['std_org']
281
+ return log
282
+
283
+
284
+ def Normalize(in_channels, norm_type='group', num_groups=32):
285
+ assert norm_type in ['group', 'batch']
286
+ if norm_type == 'group':
287
+ # TODO Changed num_groups from 32 to 8
288
+ return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
289
+ elif norm_type == 'batch':
290
+ return torch.nn.SyncBatchNorm(in_channels)
291
+
292
+
293
+ class Encoder(nn.Module):
294
+ def __init__(self, n_hiddens, downsample, image_channel=3, norm_type='group', padding_type='replicate', num_groups=32):
295
+ super().__init__()
296
+ n_times_downsample = np.array([int(math.log2(d)) for d in downsample])
297
+ self.conv_blocks = nn.ModuleList()
298
+ max_ds = n_times_downsample.max()
299
+
300
+ self.conv_first = SamePadConv3d(
301
+ image_channel, n_hiddens, kernel_size=3, padding_type=padding_type)
302
+
303
+ for i in range(max_ds):
304
+ block = nn.Module()
305
+ in_channels = n_hiddens * 2**i
306
+ out_channels = n_hiddens * 2**(i+1)
307
+ stride = tuple([2 if d > 0 else 1 for d in n_times_downsample])
308
+ block.down = SamePadConv3d(
309
+ in_channels, out_channels, 4, stride=stride, padding_type=padding_type)
310
+ block.res = ResBlock(
311
+ out_channels, out_channels, norm_type=norm_type, num_groups=num_groups)
312
+ self.conv_blocks.append(block)
313
+ n_times_downsample -= 1
314
+
315
+ self.final_block = nn.Sequential(
316
+ Normalize(out_channels, norm_type, num_groups=num_groups),
317
+ SiLU()
318
+ )
319
+
320
+ self.out_channels = out_channels
321
+
322
+ def forward(self, x):
323
+ h = self.conv_first(x)
324
+ for block in self.conv_blocks:
325
+ h = block.down(h)
326
+ h = block.res(h)
327
+ h = self.final_block(h)
328
+ return h
329
+
330
+
331
+ class Decoder(nn.Module):
332
+ def __init__(self, n_hiddens, upsample, image_channel, norm_type='group', num_groups=32):
333
+ super().__init__()
334
+
335
+ n_times_upsample = np.array([int(math.log2(d)) for d in upsample])
336
+ max_us = n_times_upsample.max()
337
+
338
+ in_channels = n_hiddens*2**max_us
339
+ self.final_block = nn.Sequential(
340
+ Normalize(in_channels, norm_type, num_groups=num_groups),
341
+ SiLU()
342
+ )
343
+
344
+ self.conv_blocks = nn.ModuleList()
345
+ for i in range(max_us):
346
+ block = nn.Module()
347
+ in_channels = in_channels if i == 0 else n_hiddens*2**(max_us-i+1)
348
+ out_channels = n_hiddens*2**(max_us-i)
349
+ us = tuple([2 if d > 0 else 1 for d in n_times_upsample])
350
+ block.up = SamePadConvTranspose3d(
351
+ in_channels, out_channels, 4, stride=us)
352
+ block.res1 = ResBlock(
353
+ out_channels, out_channels, norm_type=norm_type, num_groups=num_groups)
354
+ block.res2 = ResBlock(
355
+ out_channels, out_channels, norm_type=norm_type, num_groups=num_groups)
356
+ self.conv_blocks.append(block)
357
+ n_times_upsample -= 1
358
+
359
+ self.conv_last = SamePadConv3d(
360
+ out_channels, image_channel, kernel_size=3)
361
+
362
+ def forward(self, x):
363
+ h = self.final_block(x)
364
+ for i, block in enumerate(self.conv_blocks):
365
+ h = block.up(h)
366
+ h = block.res1(h)
367
+ h = block.res2(h)
368
+ h = self.conv_last(h)
369
+ return h
370
+
371
+
372
+ class ResBlock(nn.Module):
373
+ def __init__(self, in_channels, out_channels=None, conv_shortcut=False, dropout=0.0, norm_type='group', padding_type='replicate', num_groups=32):
374
+ super().__init__()
375
+ self.in_channels = in_channels
376
+ out_channels = in_channels if out_channels is None else out_channels
377
+ self.out_channels = out_channels
378
+ self.use_conv_shortcut = conv_shortcut
379
+
380
+ self.norm1 = Normalize(in_channels, norm_type, num_groups=num_groups)
381
+ self.conv1 = SamePadConv3d(
382
+ in_channels, out_channels, kernel_size=3, padding_type=padding_type)
383
+ self.dropout = torch.nn.Dropout(dropout)
384
+ self.norm2 = Normalize(in_channels, norm_type, num_groups=num_groups)
385
+ self.conv2 = SamePadConv3d(
386
+ out_channels, out_channels, kernel_size=3, padding_type=padding_type)
387
+ if self.in_channels != self.out_channels:
388
+ self.conv_shortcut = SamePadConv3d(
389
+ in_channels, out_channels, kernel_size=3, padding_type=padding_type)
390
+
391
+ def forward(self, x):
392
+ h = x
393
+ h = self.norm1(h)
394
+ h = silu(h)
395
+ h = self.conv1(h)
396
+ h = self.norm2(h)
397
+ h = silu(h)
398
+ h = self.conv2(h)
399
+
400
+ if self.in_channels != self.out_channels:
401
+ x = self.conv_shortcut(x)
402
+
403
+ return x+h
404
+
405
+
406
+ # Does not support dilation
407
+ class SamePadConv3d(nn.Module):
408
+ def __init__(self, in_channels, out_channels, kernel_size, stride=1, bias=True, padding_type='replicate'):
409
+ super().__init__()
410
+ if isinstance(kernel_size, int):
411
+ kernel_size = (kernel_size,) * 3
412
+ if isinstance(stride, int):
413
+ stride = (stride,) * 3
414
+
415
+ # assumes that the input shape is divisible by stride
416
+ total_pad = tuple([k - s for k, s in zip(kernel_size, stride)])
417
+ pad_input = []
418
+ for p in total_pad[::-1]: # reverse since F.pad starts from last dim
419
+ pad_input.append((p // 2 + p % 2, p // 2))
420
+ pad_input = sum(pad_input, tuple())
421
+ self.pad_input = pad_input
422
+ self.padding_type = padding_type
423
+
424
+ self.conv = nn.Conv3d(in_channels, out_channels, kernel_size,
425
+ stride=stride, padding=0, bias=bias)
426
+
427
+ def forward(self, x):
428
+ return self.conv(F.pad(x, self.pad_input, mode=self.padding_type))
429
+
430
+
431
+ class SamePadConvTranspose3d(nn.Module):
432
+ def __init__(self, in_channels, out_channels, kernel_size, stride=1, bias=True, padding_type='replicate'):
433
+ super().__init__()
434
+ if isinstance(kernel_size, int):
435
+ kernel_size = (kernel_size,) * 3
436
+ if isinstance(stride, int):
437
+ stride = (stride,) * 3
438
+
439
+ total_pad = tuple([k - s for k, s in zip(kernel_size, stride)])
440
+ pad_input = []
441
+ for p in total_pad[::-1]: # reverse since F.pad starts from last dim
442
+ pad_input.append((p // 2 + p % 2, p // 2))
443
+ pad_input = sum(pad_input, tuple())
444
+ self.pad_input = pad_input
445
+ self.padding_type = padding_type
446
+
447
+ self.convt = nn.ConvTranspose3d(in_channels, out_channels, kernel_size,
448
+ stride=stride, bias=bias,
449
+ padding=tuple([k - 1 for k in kernel_size]))
450
+
451
+ def forward(self, x):
452
+ return self.convt(F.pad(x, self.pad_input, mode=self.padding_type))
453
+
454
+
455
+ class NLayerDiscriminator(nn.Module):
456
+ def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.SyncBatchNorm, use_sigmoid=False, getIntermFeat=True):
457
+ # def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_sigmoid=False, getIntermFeat=True):
458
+ super(NLayerDiscriminator, self).__init__()
459
+ self.getIntermFeat = getIntermFeat
460
+ self.n_layers = n_layers
461
+
462
+ kw = 4
463
+ padw = int(np.ceil((kw-1.0)/2))
464
+ sequence = [[nn.Conv2d(input_nc, ndf, kernel_size=kw,
465
+ stride=2, padding=padw), nn.LeakyReLU(0.2, True)]]
466
+
467
+ nf = ndf
468
+ for n in range(1, n_layers):
469
+ nf_prev = nf
470
+ nf = min(nf * 2, 512)
471
+ sequence += [[
472
+ nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=2, padding=padw),
473
+ norm_layer(nf), nn.LeakyReLU(0.2, True)
474
+ ]]
475
+
476
+ nf_prev = nf
477
+ nf = min(nf * 2, 512)
478
+ sequence += [[
479
+ nn.Conv2d(nf_prev, nf, kernel_size=kw, stride=1, padding=padw),
480
+ norm_layer(nf),
481
+ nn.LeakyReLU(0.2, True)
482
+ ]]
483
+
484
+ sequence += [[nn.Conv2d(nf, 1, kernel_size=kw,
485
+ stride=1, padding=padw)]]
486
+
487
+ if use_sigmoid:
488
+ sequence += [[nn.Sigmoid()]]
489
+
490
+ if getIntermFeat:
491
+ for n in range(len(sequence)):
492
+ setattr(self, 'model'+str(n), nn.Sequential(*sequence[n]))
493
+ else:
494
+ sequence_stream = []
495
+ for n in range(len(sequence)):
496
+ sequence_stream += sequence[n]
497
+ self.model = nn.Sequential(*sequence_stream)
498
+
499
+ def forward(self, input):
500
+ if self.getIntermFeat:
501
+ res = [input]
502
+ for n in range(self.n_layers+2):
503
+ model = getattr(self, 'model'+str(n))
504
+ res.append(model(res[-1]))
505
+ return res[-1], res[1:]
506
+ else:
507
+ return self.model(input), _
508
+
509
+
510
+ class NLayerDiscriminator3D(nn.Module):
511
+ def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.SyncBatchNorm, use_sigmoid=False, getIntermFeat=True):
512
+ super(NLayerDiscriminator3D, self).__init__()
513
+ self.getIntermFeat = getIntermFeat
514
+ self.n_layers = n_layers
515
+
516
+ kw = 4
517
+ padw = int(np.ceil((kw-1.0)/2))
518
+ sequence = [[nn.Conv3d(input_nc, ndf, kernel_size=kw,
519
+ stride=2, padding=padw), nn.LeakyReLU(0.2, True)]]
520
+
521
+ nf = ndf
522
+ for n in range(1, n_layers):
523
+ nf_prev = nf
524
+ nf = min(nf * 2, 512)
525
+ sequence += [[
526
+ nn.Conv3d(nf_prev, nf, kernel_size=kw, stride=2, padding=padw),
527
+ norm_layer(nf), nn.LeakyReLU(0.2, True)
528
+ ]]
529
+
530
+ nf_prev = nf
531
+ nf = min(nf * 2, 512)
532
+ sequence += [[
533
+ nn.Conv3d(nf_prev, nf, kernel_size=kw, stride=1, padding=padw),
534
+ norm_layer(nf),
535
+ nn.LeakyReLU(0.2, True)
536
+ ]]
537
+
538
+ sequence += [[nn.Conv3d(nf, 1, kernel_size=kw,
539
+ stride=1, padding=padw)]]
540
+
541
+ if use_sigmoid:
542
+ sequence += [[nn.Sigmoid()]]
543
+
544
+ if getIntermFeat:
545
+ for n in range(len(sequence)):
546
+ setattr(self, 'model'+str(n), nn.Sequential(*sequence[n]))
547
+ else:
548
+ sequence_stream = []
549
+ for n in range(len(sequence)):
550
+ sequence_stream += sequence[n]
551
+ self.model = nn.Sequential(*sequence_stream)
552
+
553
+ def forward(self, input):
554
+ if self.getIntermFeat:
555
+ res = [input]
556
+ for n in range(self.n_layers+2):
557
+ model = getattr(self, 'model'+str(n))
558
+ res.append(model(res[-1]))
559
+ return res[-1], res[1:]
560
+ else:
561
+ return self.model(input), _
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/ldm/vq_gan_3d/utils.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Adapted from https://github.com/SongweiGe/TATS"""
2
+ # Copyright (c) Meta Platforms, Inc. All Rights Reserved
3
+
4
+ import warnings
5
+ import torch
6
+ import imageio
7
+
8
+ import math
9
+ import numpy as np
10
+
11
+ import sys
12
+ import pdb as pdb_original
13
+ import logging
14
+
15
+ import imageio.core.util
16
+ logging.getLogger("imageio_ffmpeg").setLevel(logging.ERROR)
17
+
18
+
19
+ class ForkedPdb(pdb_original.Pdb):
20
+ """A Pdb subclass that may be used
21
+ from a forked multiprocessing child
22
+
23
+ """
24
+
25
+ def interaction(self, *args, **kwargs):
26
+ _stdin = sys.stdin
27
+ try:
28
+ sys.stdin = open('/dev/stdin')
29
+ pdb_original.Pdb.interaction(self, *args, **kwargs)
30
+ finally:
31
+ sys.stdin = _stdin
32
+
33
+
34
+ # Shifts src_tf dim to dest dim
35
+ # i.e. shift_dim(x, 1, -1) would be (b, c, t, h, w) -> (b, t, h, w, c)
36
+ def shift_dim(x, src_dim=-1, dest_dim=-1, make_contiguous=True):
37
+ n_dims = len(x.shape)
38
+ if src_dim < 0:
39
+ src_dim = n_dims + src_dim
40
+ if dest_dim < 0:
41
+ dest_dim = n_dims + dest_dim
42
+
43
+ assert 0 <= src_dim < n_dims and 0 <= dest_dim < n_dims
44
+
45
+ dims = list(range(n_dims))
46
+ del dims[src_dim]
47
+
48
+ permutation = []
49
+ ctr = 0
50
+ for i in range(n_dims):
51
+ if i == dest_dim:
52
+ permutation.append(src_dim)
53
+ else:
54
+ permutation.append(dims[ctr])
55
+ ctr += 1
56
+ x = x.permute(permutation)
57
+ if make_contiguous:
58
+ x = x.contiguous()
59
+ return x
60
+
61
+
62
+ # reshapes tensor start from dim i (inclusive)
63
+ # to dim j (exclusive) to the desired shape
64
+ # e.g. if x.shape = (b, thw, c) then
65
+ # view_range(x, 1, 2, (t, h, w)) returns
66
+ # x of shape (b, t, h, w, c)
67
+ def view_range(x, i, j, shape):
68
+ shape = tuple(shape)
69
+
70
+ n_dims = len(x.shape)
71
+ if i < 0:
72
+ i = n_dims + i
73
+
74
+ if j is None:
75
+ j = n_dims
76
+ elif j < 0:
77
+ j = n_dims + j
78
+
79
+ assert 0 <= i < j <= n_dims
80
+
81
+ x_shape = x.shape
82
+ target_shape = x_shape[:i] + shape + x_shape[j:]
83
+ return x.view(target_shape)
84
+
85
+
86
+ def accuracy(output, target, topk=(1,)):
87
+ """Computes the accuracy over the k top predictions for the specified values of k"""
88
+ with torch.no_grad():
89
+ maxk = max(topk)
90
+ batch_size = target.size(0)
91
+
92
+ _, pred = output.topk(maxk, 1, True, True)
93
+ pred = pred.t()
94
+ correct = pred.eq(target.reshape(1, -1).expand_as(pred))
95
+
96
+ res = []
97
+ for k in topk:
98
+ correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True)
99
+ res.append(correct_k.mul_(100.0 / batch_size))
100
+ return res
101
+
102
+
103
+ def tensor_slice(x, begin, size):
104
+ assert all([b >= 0 for b in begin])
105
+ size = [l - b if s == -1 else s
106
+ for s, b, l in zip(size, begin, x.shape)]
107
+ assert all([s >= 0 for s in size])
108
+
109
+ slices = [slice(b, b + s) for b, s in zip(begin, size)]
110
+ return x[slices]
111
+
112
+
113
+ def adopt_weight(global_step, threshold=0, value=0.):
114
+ weight = 1
115
+ if global_step < threshold:
116
+ weight = value
117
+ return weight
118
+
119
+
120
+ def save_video_grid(video, fname, nrow=None, fps=6):
121
+ b, c, t, h, w = video.shape
122
+ video = video.permute(0, 2, 3, 4, 1)
123
+ video = (video.cpu().numpy() * 255).astype('uint8')
124
+ if nrow is None:
125
+ nrow = math.ceil(math.sqrt(b))
126
+ ncol = math.ceil(b / nrow)
127
+ padding = 1
128
+ video_grid = np.zeros((t, (padding + h) * nrow + padding,
129
+ (padding + w) * ncol + padding, c), dtype='uint8')
130
+ for i in range(b):
131
+ r = i // ncol
132
+ c = i % ncol
133
+ start_r = (padding + h) * r
134
+ start_c = (padding + w) * c
135
+ video_grid[:, start_r:start_r + h, start_c:start_c + w] = video[i]
136
+ video = []
137
+ for i in range(t):
138
+ video.append(video_grid[i])
139
+ imageio.mimsave(fname, video, fps=fps)
140
+ ## skvideo.io.vwrite(fname, video_grid, inputdict={'-r': '5'})
141
+ #print('saved videos to', fname)
142
+
143
+
144
+ def comp_getattr(args, attr_name, default=None):
145
+ if hasattr(args, attr_name):
146
+ return getattr(args, attr_name)
147
+ else:
148
+ return default
149
+
150
+
151
+ def visualize_tensors(t, name=None, nest=0):
152
+ if name is not None:
153
+ print(name, "current nest: ", nest)
154
+ print("type: ", type(t))
155
+ if 'dict' in str(type(t)):
156
+ print(t.keys())
157
+ for k in t.keys():
158
+ if t[k] is None:
159
+ print(k, "None")
160
+ else:
161
+ if 'Tensor' in str(type(t[k])):
162
+ print(k, t[k].shape)
163
+ elif 'dict' in str(type(t[k])):
164
+ print(k, 'dict')
165
+ visualize_tensors(t[k], name, nest + 1)
166
+ elif 'list' in str(type(t[k])):
167
+ print(k, len(t[k]))
168
+ visualize_tensors(t[k], name, nest + 1)
169
+ elif 'list' in str(type(t)):
170
+ print("list length: ", len(t))
171
+ for t2 in t:
172
+ visualize_tensors(t2, name, nest + 1)
173
+ elif 'Tensor' in str(type(t)):
174
+ print(t.shape)
175
+ else:
176
+ print(t)
177
+ return ""
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_kidney_fold0_early.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d889b3561803f7490f4050c03a02163f099633e4f00fea4cb10b5b993685e5cc
3
+ size 290138333
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_kidney_fold0_noearly_t200.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26bc7847ae15377a5586535cbb2e6a1ec5b6a98732f7f795c284d7dcda208c97
3
+ size 290156765
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_liver_fold0_early.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0135000f031f741252b3e706748b674d33e7278402a7cb2500fec5f4966847bd
3
+ size 290138333
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_liver_fold0_noearly_t200.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2a21980e53efd6758ae92e79a82668f0e1e6d9b52fdf6b2a709cb929ebedb3b
3
+ size 290156765
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_pancreas_fold0_early.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9438e39a44af92bb0fbaf5cc50a3ac3aaa260978a69ac341ed7ec23512c080a5
3
+ size 290138333
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/diff_pancreas_fold0_noearly_t200.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb37011840156f548fd2348dbb5578f9bc81de16719ec226fbef2de6f0244f9d
3
+ size 290156765
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/model_weight/recon_96d4_all.ckpt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef88523af9590a7325bc9ca41999de191c3fbc41afc6186a8c4db5528446bb1f
3
+ size 242615727
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/utils.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Tumor Generateion
2
+ import random
3
+ import cv2
4
+ import elasticdeform
5
+ import numpy as np
6
+ from scipy.ndimage import gaussian_filter
7
+ from TumorGeneration.ldm.ddpm.ddim import DDIMSampler
8
+
9
+ # Step 1: Random select (numbers) location for tumor.
10
+ def random_select(mask_scan, organ_type):
11
+ # we first find z index and then sample point with z slice
12
+ # print('mask_scan',np.unique(mask_scan))
13
+ # print('pixel num', (mask_scan == 1).sum())
14
+ z_start, z_end = np.where(np.any(mask_scan, axis=(0, 1)))[0].min(), np.where(np.any(mask_scan, axis=(0, 1)))[0].max()
15
+ # print('z_start, z_end',z_start, z_end)
16
+ # we need to strict number z's position (0.3 - 0.7 in the middle of liver)
17
+ while 1:
18
+ z = round(random.uniform(0.3, 0.7) * (z_end - z_start)) + z_start
19
+ liver_mask = mask_scan[..., z]
20
+ # erode the mask (we don't want the edge points)
21
+ if organ_type == 'liver':
22
+ kernel = np.ones((5,5), dtype=np.uint8)
23
+ liver_mask = cv2.erode(liver_mask, kernel, iterations=1)
24
+ if (liver_mask == 1).sum() > 0:
25
+ break
26
+
27
+
28
+
29
+ # print('liver_mask', (liver_mask == 1).sum())
30
+ coordinates = np.argwhere(liver_mask == 1)
31
+ random_index = np.random.randint(0, len(coordinates))
32
+ xyz = coordinates[random_index].tolist() # get x,y
33
+ xyz.append(z)
34
+ potential_points = xyz
35
+
36
+ return potential_points
37
+
38
+ def center_select(mask_scan):
39
+ z_start, z_end = np.where(np.any(mask_scan, axis=(0, 1)))[0].min(), np.where(np.any(mask_scan, axis=(0, 1)))[0].max()
40
+ x_start, x_end = np.where(np.any(mask_scan, axis=(1, 2)))[0].min(), np.where(np.any(mask_scan, axis=(1, 2)))[0].max()
41
+ y_start, y_end = np.where(np.any(mask_scan, axis=(0, 2)))[0].min(), np.where(np.any(mask_scan, axis=(0, 2)))[0].max()
42
+
43
+ z = round(0.5 * (z_end - z_start)) + z_start
44
+ x = round(0.5 * (x_end - x_start)) + x_start
45
+ y = round(0.5 * (y_end - y_start)) + y_start
46
+
47
+ xyz = [x, y, z]
48
+ potential_points = xyz
49
+
50
+ return potential_points
51
+
52
+ # Step 2 : generate the ellipsoid
53
+ def get_ellipsoid(x, y, z):
54
+ """"
55
+ x, y, z is the radius of this ellipsoid in x, y, z direction respectly.
56
+ """
57
+ sh = (4*x, 4*y, 4*z)
58
+ out = np.zeros(sh, int)
59
+ aux = np.zeros(sh)
60
+ radii = np.array([x, y, z])
61
+ com = np.array([2*x, 2*y, 2*z]) # center point
62
+
63
+ # calculate the ellipsoid
64
+ bboxl = np.floor(com-radii).clip(0,None).astype(int)
65
+ bboxh = (np.ceil(com+radii)+1).clip(None, sh).astype(int)
66
+ roi = out[tuple(map(slice,bboxl,bboxh))]
67
+ roiaux = aux[tuple(map(slice,bboxl,bboxh))]
68
+ logrid = *map(np.square,np.ogrid[tuple(
69
+ map(slice,(bboxl-com)/radii,(bboxh-com-1)/radii,1j*(bboxh-bboxl)))]),
70
+ dst = (1-sum(logrid)).clip(0,None)
71
+ mask = dst>roiaux
72
+ roi[mask] = 1
73
+ np.copyto(roiaux,dst,where=mask)
74
+
75
+ return out
76
+
77
+ def get_fixed_geo(mask_scan, tumor_type, organ_type):
78
+ if tumor_type == 'large':
79
+ enlarge_x, enlarge_y, enlarge_z = 280, 280, 280
80
+ else:
81
+ enlarge_x, enlarge_y, enlarge_z = 160, 160, 160
82
+ geo_mask = np.zeros((mask_scan.shape[0] + enlarge_x, mask_scan.shape[1] + enlarge_y, mask_scan.shape[2] + enlarge_z), dtype=np.int8)
83
+ tiny_radius, small_radius, medium_radius, large_radius = 4, 8, 16, 32
84
+
85
+ if tumor_type == 'tiny':
86
+ num_tumor = random.randint(1,3)
87
+ # num_tumor = 1
88
+ for _ in range(num_tumor):
89
+ # Tiny tumor
90
+ x = random.randint(int(0.75*tiny_radius), int(1.25*tiny_radius))
91
+ y = random.randint(int(0.75*tiny_radius), int(1.25*tiny_radius))
92
+ z = random.randint(int(0.75*tiny_radius), int(1.25*tiny_radius))
93
+ sigma = random.uniform(0.5,1)
94
+
95
+ geo = get_ellipsoid(x, y, z)
96
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
97
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
98
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
99
+ point = random_select(mask_scan, organ_type)
100
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
101
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
102
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
103
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
104
+
105
+ # paste small tumor geo into test sample
106
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
107
+
108
+ if tumor_type == 'small':
109
+ num_tumor = random.randint(1,3)
110
+ # num_tumor = 1
111
+ for _ in range(num_tumor):
112
+ # Small tumor
113
+ x = random.randint(int(0.75*small_radius), int(1.25*small_radius))
114
+ y = random.randint(int(0.75*small_radius), int(1.25*small_radius))
115
+ z = random.randint(int(0.75*small_radius), int(1.25*small_radius))
116
+ sigma = random.randint(1, 2)
117
+
118
+ geo = get_ellipsoid(x, y, z)
119
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
120
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
121
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
122
+ # texture = get_texture((4*x, 4*y, 4*z))
123
+ point = random_select(mask_scan, organ_type)
124
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
125
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
126
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
127
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
128
+
129
+ # paste small tumor geo into test sample
130
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
131
+ # texture_map[x_low:x_high, y_low:y_high, z_low:z_high] = texture
132
+
133
+ if tumor_type == 'medium':
134
+ # num_tumor = random.randint(1, 3)
135
+ num_tumor = 1
136
+ for _ in range(num_tumor):
137
+ # medium tumor
138
+ x = random.randint(int(0.75*medium_radius), int(1.25*medium_radius))
139
+ y = random.randint(int(0.75*medium_radius), int(1.25*medium_radius))
140
+ z = random.randint(int(0.75*medium_radius), int(1.25*medium_radius))
141
+ sigma = random.randint(3, 6)
142
+
143
+ geo = get_ellipsoid(x, y, z)
144
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
145
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
146
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
147
+ # texture = get_texture((4*x, 4*y, 4*z))
148
+ point = random_select(mask_scan, organ_type)
149
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
150
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
151
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
152
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
153
+
154
+ # paste medium tumor geo into test sample
155
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
156
+ # texture_map[x_low:x_high, y_low:y_high, z_low:z_high] = texture
157
+
158
+ if tumor_type == 'large':
159
+ num_tumor = 1 # random.randint(1,3)
160
+ for _ in range(num_tumor):
161
+ # Large tumor
162
+
163
+ x = random.randint(int(0.75*large_radius), int(1.25*large_radius))
164
+ y = random.randint(int(0.75*large_radius), int(1.25*large_radius))
165
+ z = random.randint(int(0.75*large_radius), int(1.25*large_radius))
166
+ sigma = random.randint(5, 10)
167
+
168
+ geo = get_ellipsoid(x, y, z)
169
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
170
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
171
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
172
+ if organ_type == 'liver' or organ_type == 'kidney' :
173
+ point = random_select(mask_scan, organ_type)
174
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
175
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
176
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
177
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
178
+ else:
179
+ x_start, x_end = np.where(np.any(geo, axis=(1, 2)))[0].min(), np.where(np.any(geo, axis=(1, 2)))[0].max()
180
+ y_start, y_end = np.where(np.any(geo, axis=(0, 2)))[0].min(), np.where(np.any(geo, axis=(0, 2)))[0].max()
181
+ z_start, z_end = np.where(np.any(geo, axis=(0, 1)))[0].min(), np.where(np.any(geo, axis=(0, 1)))[0].max()
182
+ geo = geo[x_start:x_end, y_start:y_end, z_start:z_end]
183
+
184
+ point = center_select(mask_scan)
185
+
186
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
187
+ x_low = new_point[0] - geo.shape[0]//2
188
+ y_low = new_point[1] - geo.shape[1]//2
189
+ z_low = new_point[2] - geo.shape[2]//2
190
+
191
+ # paste small tumor geo into test sample
192
+ geo_mask[x_low:x_low+geo.shape[0], y_low:y_low+geo.shape[1], z_low:z_low+geo.shape[2]] += geo
193
+
194
+ geo_mask = geo_mask[enlarge_x//2:-enlarge_x//2, enlarge_y//2:-enlarge_y//2, enlarge_z//2:-enlarge_z//2]
195
+ # texture_map = texture_map[enlarge_x//2:-enlarge_x//2, enlarge_y//2:-enlarge_y//2, enlarge_z//2:-enlarge_z//2]
196
+ if ((tumor_type == 'medium') or (tumor_type == 'large')) and (organ_type == 'kidney'):
197
+ if random.random() > 0.5:
198
+ geo_mask = (geo_mask>=1)
199
+ else:
200
+ geo_mask = (geo_mask * mask_scan) >=1
201
+ else:
202
+ geo_mask = (geo_mask * mask_scan) >=1
203
+
204
+ return geo_mask
205
+
206
+
207
+ from .ldm.vq_gan_3d.model.vqgan import VQGAN
208
+ import matplotlib.pyplot as plt
209
+ import SimpleITK as sitk
210
+ from .ldm.ddpm import Unet3D, GaussianDiffusion, Tester
211
+ from hydra import initialize, compose
212
+ import torch
213
+ import yaml
214
+ def synt_model_prepare(device, vqgan_ckpt='TumorGeneration/model_weight/recon_96d4_all.ckpt', diffusion_ckpt='TumorGeneration/model_weight/', fold=0, organ='liver'):
215
+ with initialize(config_path="diffusion_config/"):
216
+ cfg=compose(config_name="ddpm.yaml")
217
+ print('diffusion_ckpt',diffusion_ckpt)
218
+ vqgan = VQGAN.load_from_checkpoint(vqgan_ckpt)
219
+ vqgan = vqgan.to(device)
220
+ vqgan.eval()
221
+
222
+ early_Unet3D = Unet3D(
223
+ dim=cfg.diffusion_img_size,
224
+ dim_mults=cfg.dim_mults,
225
+ channels=cfg.diffusion_num_channels,
226
+ out_dim=cfg.out_dim
227
+ ).to(device)
228
+
229
+ early_diffusion = GaussianDiffusion(
230
+ early_Unet3D,
231
+ vqgan_ckpt= vqgan_ckpt, # cfg.vqgan_ckpt,
232
+ image_size=cfg.diffusion_img_size,
233
+ num_frames=cfg.diffusion_depth_size,
234
+ channels=cfg.diffusion_num_channels,
235
+ timesteps=4, # cfg.timesteps,
236
+ loss_type=cfg.loss_type,
237
+ device=device
238
+ ).to(device)
239
+
240
+ noearly_Unet3D = Unet3D(
241
+ dim=cfg.diffusion_img_size,
242
+ dim_mults=cfg.dim_mults,
243
+ channels=cfg.diffusion_num_channels,
244
+ out_dim=cfg.out_dim
245
+ ).to(device)
246
+
247
+ noearly_diffusion = GaussianDiffusion(
248
+ noearly_Unet3D,
249
+ vqgan_ckpt= vqgan_ckpt, # cfg.vqgan_ckpt,
250
+ image_size=cfg.diffusion_img_size,
251
+ num_frames=cfg.diffusion_depth_size,
252
+ channels=cfg.diffusion_num_channels,
253
+ timesteps=200, # cfg.timesteps,
254
+ loss_type=cfg.loss_type,
255
+ device=device
256
+ ).to(device)
257
+
258
+ early_tester = Tester(early_diffusion)
259
+ # noearly_tester = Tester(noearly_diffusion)
260
+ early_tester.load(diffusion_ckpt+'diff_{}_fold{}_early.pt'.format(organ, fold), map_location=device)
261
+ # noearly_tester.load(diffusion_ckpt+'diff_liver_fold{}_noearly_t200.pt'.format(fold), map_location=device)
262
+
263
+ # early_checkpoint = torch.load(diffusion_ckpt+'diff_liver_fold{}_early.pt'.format(fold), map_location=device)
264
+ noearly_checkpoint = torch.load(diffusion_ckpt+'diff_{}_fold{}_noearly_t200.pt'.format(organ, fold), map_location=device)
265
+ # early_diffusion.load_state_dict(early_checkpoint['ema'])
266
+ noearly_diffusion.load_state_dict(noearly_checkpoint['ema'])
267
+ # early_sampler = DDIMSampler(early_diffusion, schedule="cosine")
268
+ noearly_sampler = DDIMSampler(noearly_diffusion, schedule="cosine")
269
+ # breakpoint()
270
+ return vqgan, early_tester, noearly_sampler
271
+
272
+ def synthesize_early_tumor(ct_volume, organ_mask, organ_type, vqgan, tester):
273
+ device=ct_volume.device
274
+
275
+ # generate tumor mask
276
+ tumor_types = ['tiny', 'small']
277
+ # tumor_probs = np.array([0.5, 0.5])
278
+ tumor_probs = np.array([0.2, 0.8])
279
+ total_tumor_mask = []
280
+ organ_mask_np = organ_mask.cpu().numpy()
281
+ with torch.no_grad():
282
+ # get model input
283
+ for bs in range(organ_mask_np.shape[0]):
284
+ synthetic_tumor_type = np.random.choice(tumor_types, p=tumor_probs.ravel())
285
+ tumor_mask = get_fixed_geo(organ_mask_np[bs,0], synthetic_tumor_type, organ_type)
286
+ total_tumor_mask.append(torch.from_numpy(tumor_mask)[None,:])
287
+ total_tumor_mask = torch.stack(total_tumor_mask, dim=0).to(dtype=torch.float32, device=device)
288
+
289
+ volume = ct_volume*2.0 - 1.0
290
+ mask = total_tumor_mask*2.0 - 1.0
291
+ mask_ = 1-total_tumor_mask
292
+ masked_volume = (volume*mask_).detach()
293
+
294
+ volume = volume.permute(0,1,-1,-3,-2)
295
+ masked_volume = masked_volume.permute(0,1,-1,-3,-2)
296
+ mask = mask.permute(0,1,-1,-3,-2)
297
+
298
+ # vqgan encoder inference
299
+ masked_volume_feat = vqgan.encode(masked_volume, quantize=False, include_embeddings=True)
300
+ masked_volume_feat = ((masked_volume_feat - vqgan.codebook.embeddings.min()) /
301
+ (vqgan.codebook.embeddings.max() - vqgan.codebook.embeddings.min())) * 2.0 - 1.0
302
+
303
+ cc = torch.nn.functional.interpolate(mask, size=masked_volume_feat.shape[-3:])
304
+ cond = torch.cat((masked_volume_feat, cc), dim=1)
305
+
306
+ # diffusion inference and decoder
307
+ tester.ema_model.eval()
308
+ sample = tester.ema_model.sample(batch_size=volume.shape[0], cond=cond)
309
+
310
+ # if organ_type == 'liver' or organ_type == 'kidney' :
311
+
312
+ mask_01 = torch.clamp((mask+1.0)/2.0, min=0.0, max=1.0)
313
+ sigma = np.random.uniform(0, 4) # (1, 2)
314
+ mask_01_np_blur = gaussian_filter(mask_01.cpu().numpy()*1.0, sigma=[0,0,sigma,sigma,sigma])
315
+ # mask_01_np_blur = mask_01_np_blur*mask_01.cpu().numpy()
316
+
317
+ volume_ = torch.clamp((volume+1.0)/2.0, min=0.0, max=1.0)
318
+ sample_ = torch.clamp((sample+1.0)/2.0, min=0.0, max=1.0)
319
+
320
+ mask_01_blur = torch.from_numpy(mask_01_np_blur).to(device=device)
321
+ final_volume_ = (1-mask_01_blur)*volume_ +mask_01_blur*sample_
322
+ final_volume_ = torch.clamp(final_volume_, min=0.0, max=1.0)
323
+ # elif organ_type == 'pancreas':
324
+ # final_volume_ = (sample+1.0)/2.0
325
+ final_volume_ = final_volume_.permute(0,1,-2,-1,-3)
326
+ organ_tumor_mask = torch.ones_like(organ_mask)
327
+ organ_tumor_mask[total_tumor_mask==1] = 2
328
+
329
+ return final_volume_, organ_tumor_mask
330
+
331
+ def synthesize_medium_tumor(ct_volume, organ_mask, organ_type, vqgan, sampler, ddim_ts=50):
332
+ device=ct_volume.device
333
+
334
+ # generate tumor mask
335
+ # tumor_types = ['large']
336
+ # tumor_probs = np.array([1.0])
337
+ total_tumor_mask = []
338
+ organ_mask_np = organ_mask.cpu().numpy()
339
+ with torch.no_grad():
340
+ # get model input
341
+ for bs in range(organ_mask_np.shape[0]):
342
+ # synthetic_tumor_type = np.random.choice(tumor_types, p=tumor_probs.ravel())
343
+ synthetic_tumor_type = 'medium'
344
+ tumor_mask = get_fixed_geo(organ_mask_np[bs,0], synthetic_tumor_type, organ_type)
345
+ total_tumor_mask.append(torch.from_numpy(tumor_mask)[None,:])
346
+ total_tumor_mask = torch.stack(total_tumor_mask, dim=0).to(dtype=torch.float32, device=device)
347
+
348
+ volume = ct_volume*2.0 - 1.0
349
+ mask = total_tumor_mask*2.0 - 1.0
350
+ mask_ = 1-total_tumor_mask
351
+ masked_volume = (volume*mask_).detach()
352
+
353
+ volume = volume.permute(0,1,-1,-3,-2)
354
+ masked_volume = masked_volume.permute(0,1,-1,-3,-2)
355
+ mask = mask.permute(0,1,-1,-3,-2)
356
+
357
+ # vqgan encoder inference
358
+ masked_volume_feat = vqgan.encode(masked_volume, quantize=False, include_embeddings=True)
359
+ masked_volume_feat = ((masked_volume_feat - vqgan.codebook.embeddings.min()) /
360
+ (vqgan.codebook.embeddings.max() - vqgan.codebook.embeddings.min())) * 2.0 - 1.0
361
+
362
+ cc = torch.nn.functional.interpolate(mask, size=masked_volume_feat.shape[-3:])
363
+ cond = torch.cat((masked_volume_feat, cc), dim=1)
364
+
365
+ # diffusion inference and decoder
366
+ shape = masked_volume_feat.shape[-4:]
367
+ samples_ddim, _ = sampler.sample(S=ddim_ts,
368
+ conditioning=cond,
369
+ batch_size=1,
370
+ shape=shape,
371
+ verbose=False)
372
+ samples_ddim = (((samples_ddim + 1.0) / 2.0) * (vqgan.codebook.embeddings.max() -
373
+ vqgan.codebook.embeddings.min())) + vqgan.codebook.embeddings.min()
374
+
375
+ sample = vqgan.decode(samples_ddim, quantize=True)
376
+
377
+ # if organ_type == 'liver' or organ_type == 'kidney':
378
+ # post-process
379
+ mask_01 = torch.clamp((mask+1.0)/2.0, min=0.0, max=1.0)
380
+ sigma = np.random.uniform(0, 4) # (1, 2)
381
+ mask_01_np_blur = gaussian_filter(mask_01.cpu().numpy()*1.0, sigma=[0,0,sigma,sigma,sigma])
382
+ # mask_01_np_blur = mask_01_np_blur*mask_01.cpu().numpy()
383
+
384
+ volume_ = torch.clamp((volume+1.0)/2.0, min=0.0, max=1.0)
385
+ sample_ = torch.clamp((sample+1.0)/2.0, min=0.0, max=1.0)
386
+
387
+ mask_01_blur = torch.from_numpy(mask_01_np_blur).to(device=device)
388
+ final_volume_ = (1-mask_01_blur)*volume_ +mask_01_blur*sample_
389
+ final_volume_ = torch.clamp(final_volume_, min=0.0, max=1.0)
390
+ # elif organ_type == 'pancreas':
391
+ # final_volume_ = (sample+1.0)/2.0
392
+
393
+ final_volume_ = final_volume_.permute(0,1,-2,-1,-3)
394
+ organ_tumor_mask = torch.ones_like(organ_mask)
395
+ organ_tumor_mask[total_tumor_mask==1] = 2
396
+
397
+ return final_volume_, organ_tumor_mask
398
+
399
+ def synthesize_large_tumor(ct_volume, organ_mask, organ_type, vqgan, sampler, ddim_ts=50):
400
+ device=ct_volume.device
401
+
402
+ # generate tumor mask
403
+ # tumor_types = ['large']
404
+ # tumor_probs = np.array([1.0])
405
+ total_tumor_mask = []
406
+ organ_mask_np = organ_mask.cpu().numpy()
407
+ with torch.no_grad():
408
+ # get model input
409
+ for bs in range(organ_mask_np.shape[0]):
410
+ # synthetic_tumor_type = np.random.choice(tumor_types, p=tumor_probs.ravel())
411
+ synthetic_tumor_type = 'large'
412
+ tumor_mask = get_fixed_geo(organ_mask_np[bs,0], synthetic_tumor_type, organ_type)
413
+ total_tumor_mask.append(torch.from_numpy(tumor_mask)[None,:])
414
+ total_tumor_mask = torch.stack(total_tumor_mask, dim=0).to(dtype=torch.float32, device=device)
415
+
416
+ volume = ct_volume*2.0 - 1.0
417
+ mask = total_tumor_mask*2.0 - 1.0
418
+ mask_ = 1-total_tumor_mask
419
+ masked_volume = (volume*mask_).detach()
420
+
421
+ volume = volume.permute(0,1,-1,-3,-2)
422
+ masked_volume = masked_volume.permute(0,1,-1,-3,-2)
423
+ mask = mask.permute(0,1,-1,-3,-2)
424
+
425
+ # vqgan encoder inference
426
+ masked_volume_feat = vqgan.encode(masked_volume, quantize=False, include_embeddings=True)
427
+ masked_volume_feat = ((masked_volume_feat - vqgan.codebook.embeddings.min()) /
428
+ (vqgan.codebook.embeddings.max() - vqgan.codebook.embeddings.min())) * 2.0 - 1.0
429
+
430
+ cc = torch.nn.functional.interpolate(mask, size=masked_volume_feat.shape[-3:])
431
+ cond = torch.cat((masked_volume_feat, cc), dim=1)
432
+
433
+ # diffusion inference and decoder
434
+ shape = masked_volume_feat.shape[-4:]
435
+ samples_ddim, _ = sampler.sample(S=ddim_ts,
436
+ conditioning=cond,
437
+ batch_size=1,
438
+ shape=shape,
439
+ verbose=False)
440
+ samples_ddim = (((samples_ddim + 1.0) / 2.0) * (vqgan.codebook.embeddings.max() -
441
+ vqgan.codebook.embeddings.min())) + vqgan.codebook.embeddings.min()
442
+
443
+ sample = vqgan.decode(samples_ddim, quantize=True)
444
+
445
+ # if organ_type == 'liver' or organ_type == 'kidney':
446
+ # post-process
447
+ mask_01 = torch.clamp((mask+1.0)/2.0, min=0.0, max=1.0)
448
+ sigma = np.random.uniform(0, 4) # (1, 2)
449
+ mask_01_np_blur = gaussian_filter(mask_01.cpu().numpy()*1.0, sigma=[0,0,sigma,sigma,sigma])
450
+ # mask_01_np_blur = mask_01_np_blur*mask_01.cpu().numpy()
451
+
452
+ volume_ = torch.clamp((volume+1.0)/2.0, min=0.0, max=1.0)
453
+ sample_ = torch.clamp((sample+1.0)/2.0, min=0.0, max=1.0)
454
+
455
+ mask_01_blur = torch.from_numpy(mask_01_np_blur).to(device=device)
456
+ final_volume_ = (1-mask_01_blur)*volume_ +mask_01_blur*sample_
457
+ final_volume_ = torch.clamp(final_volume_, min=0.0, max=1.0)
458
+ # elif organ_type == 'pancreas':
459
+ # final_volume_ = (sample+1.0)/2.0
460
+
461
+ final_volume_ = final_volume_.permute(0,1,-2,-1,-3)
462
+ organ_tumor_mask = torch.ones_like(organ_mask)
463
+ organ_tumor_mask[total_tumor_mask==1] = 2
464
+
465
+ return final_volume_, organ_tumor_mask
Generation_Pipeline_filter_all2/syn_pancreas/TumorGeneration/utils_.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Tumor Generateion
2
+ import random
3
+ import cv2
4
+ import elasticdeform
5
+ import numpy as np
6
+ from scipy.ndimage import gaussian_filter
7
+
8
+ # Step 1: Random select (numbers) location for tumor.
9
+ def random_select(mask_scan):
10
+ # we first find z index and then sample point with z slice
11
+ z_start, z_end = np.where(np.any(mask_scan, axis=(0, 1)))[0][[0, -1]]
12
+
13
+ # we need to strict number z's position (0.3 - 0.7 in the middle of liver)
14
+ z = round(random.uniform(0.3, 0.7) * (z_end - z_start)) + z_start
15
+
16
+ liver_mask = mask_scan[..., z]
17
+
18
+ # erode the mask (we don't want the edge points)
19
+ kernel = np.ones((5,5), dtype=np.uint8)
20
+ liver_mask = cv2.erode(liver_mask, kernel, iterations=1)
21
+
22
+ coordinates = np.argwhere(liver_mask == 1)
23
+ random_index = np.random.randint(0, len(coordinates))
24
+ xyz = coordinates[random_index].tolist() # get x,y
25
+ xyz.append(z)
26
+ potential_points = xyz
27
+
28
+ return potential_points
29
+
30
+ # Step 2 : generate the ellipsoid
31
+ def get_ellipsoid(x, y, z):
32
+ """"
33
+ x, y, z is the radius of this ellipsoid in x, y, z direction respectly.
34
+ """
35
+ sh = (4*x, 4*y, 4*z)
36
+ out = np.zeros(sh, int)
37
+ aux = np.zeros(sh)
38
+ radii = np.array([x, y, z])
39
+ com = np.array([2*x, 2*y, 2*z]) # center point
40
+
41
+ # calculate the ellipsoid
42
+ bboxl = np.floor(com-radii).clip(0,None).astype(int)
43
+ bboxh = (np.ceil(com+radii)+1).clip(None, sh).astype(int)
44
+ roi = out[tuple(map(slice,bboxl,bboxh))]
45
+ roiaux = aux[tuple(map(slice,bboxl,bboxh))]
46
+ logrid = *map(np.square,np.ogrid[tuple(
47
+ map(slice,(bboxl-com)/radii,(bboxh-com-1)/radii,1j*(bboxh-bboxl)))]),
48
+ dst = (1-sum(logrid)).clip(0,None)
49
+ mask = dst>roiaux
50
+ roi[mask] = 1
51
+ np.copyto(roiaux,dst,where=mask)
52
+
53
+ return out
54
+
55
+ def get_fixed_geo(mask_scan, tumor_type):
56
+
57
+ enlarge_x, enlarge_y, enlarge_z = 160, 160, 160
58
+ geo_mask = np.zeros((mask_scan.shape[0] + enlarge_x, mask_scan.shape[1] + enlarge_y, mask_scan.shape[2] + enlarge_z), dtype=np.int8)
59
+ tiny_radius, small_radius, medium_radius, large_radius = 4, 8, 16, 32
60
+
61
+ if tumor_type == 'tiny':
62
+ num_tumor = random.randint(3,10)
63
+ for _ in range(num_tumor):
64
+ # Tiny tumor
65
+ x = random.randint(int(0.75*tiny_radius), int(1.25*tiny_radius))
66
+ y = random.randint(int(0.75*tiny_radius), int(1.25*tiny_radius))
67
+ z = random.randint(int(0.75*tiny_radius), int(1.25*tiny_radius))
68
+ sigma = random.uniform(0.5,1)
69
+
70
+ geo = get_ellipsoid(x, y, z)
71
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
72
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
73
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
74
+ point = random_select(mask_scan)
75
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
76
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
77
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
78
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
79
+
80
+ # paste small tumor geo into test sample
81
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
82
+
83
+ if tumor_type == 'small':
84
+ num_tumor = random.randint(3,10)
85
+ for _ in range(num_tumor):
86
+ # Small tumor
87
+ x = random.randint(int(0.75*small_radius), int(1.25*small_radius))
88
+ y = random.randint(int(0.75*small_radius), int(1.25*small_radius))
89
+ z = random.randint(int(0.75*small_radius), int(1.25*small_radius))
90
+ sigma = random.randint(1, 2)
91
+
92
+ geo = get_ellipsoid(x, y, z)
93
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
94
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
95
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
96
+ # texture = get_texture((4*x, 4*y, 4*z))
97
+ point = random_select(mask_scan)
98
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
99
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
100
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
101
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
102
+
103
+ # paste small tumor geo into test sample
104
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
105
+ # texture_map[x_low:x_high, y_low:y_high, z_low:z_high] = texture
106
+
107
+ if tumor_type == 'medium':
108
+ num_tumor = random.randint(2, 5)
109
+ for _ in range(num_tumor):
110
+ # medium tumor
111
+ x = random.randint(int(0.75*medium_radius), int(1.25*medium_radius))
112
+ y = random.randint(int(0.75*medium_radius), int(1.25*medium_radius))
113
+ z = random.randint(int(0.75*medium_radius), int(1.25*medium_radius))
114
+ sigma = random.randint(3, 6)
115
+
116
+ geo = get_ellipsoid(x, y, z)
117
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
118
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
119
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
120
+ # texture = get_texture((4*x, 4*y, 4*z))
121
+ point = random_select(mask_scan)
122
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
123
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
124
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
125
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
126
+
127
+ # paste medium tumor geo into test sample
128
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
129
+ # texture_map[x_low:x_high, y_low:y_high, z_low:z_high] = texture
130
+
131
+ if tumor_type == 'large':
132
+ num_tumor = random.randint(1,3)
133
+ for _ in range(num_tumor):
134
+ # Large tumor
135
+ x = random.randint(int(0.75*large_radius), int(1.25*large_radius))
136
+ y = random.randint(int(0.75*large_radius), int(1.25*large_radius))
137
+ z = random.randint(int(0.75*large_radius), int(1.25*large_radius))
138
+ sigma = random.randint(5, 10)
139
+
140
+ geo = get_ellipsoid(x, y, z)
141
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
142
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
143
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
144
+ # texture = get_texture((4*x, 4*y, 4*z))
145
+ point = random_select(mask_scan)
146
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
147
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
148
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
149
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
150
+
151
+ # paste small tumor geo into test sample
152
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
153
+ # texture_map[x_low:x_high, y_low:y_high, z_low:z_high] = texture
154
+
155
+ if tumor_type == "mix":
156
+ # tiny
157
+ num_tumor = random.randint(3,10)
158
+ for _ in range(num_tumor):
159
+ # Tiny tumor
160
+ x = random.randint(int(0.75*tiny_radius), int(1.25*tiny_radius))
161
+ y = random.randint(int(0.75*tiny_radius), int(1.25*tiny_radius))
162
+ z = random.randint(int(0.75*tiny_radius), int(1.25*tiny_radius))
163
+ sigma = random.uniform(0.5,1)
164
+
165
+ geo = get_ellipsoid(x, y, z)
166
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
167
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
168
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
169
+ point = random_select(mask_scan)
170
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
171
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
172
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
173
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
174
+
175
+ # paste small tumor geo into test sample
176
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
177
+
178
+ # small
179
+ num_tumor = random.randint(5,10)
180
+ for _ in range(num_tumor):
181
+ # Small tumor
182
+ x = random.randint(int(0.75*small_radius), int(1.25*small_radius))
183
+ y = random.randint(int(0.75*small_radius), int(1.25*small_radius))
184
+ z = random.randint(int(0.75*small_radius), int(1.25*small_radius))
185
+ sigma = random.randint(1, 2)
186
+
187
+ geo = get_ellipsoid(x, y, z)
188
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
189
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
190
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
191
+ # texture = get_texture((4*x, 4*y, 4*z))
192
+ point = random_select(mask_scan)
193
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
194
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
195
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
196
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
197
+
198
+ # paste small tumor geo into test sample
199
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
200
+ # texture_map[x_low:x_high, y_low:y_high, z_low:z_high] = texture
201
+
202
+ # medium
203
+ num_tumor = random.randint(2, 5)
204
+ for _ in range(num_tumor):
205
+ # medium tumor
206
+ x = random.randint(int(0.75*medium_radius), int(1.25*medium_radius))
207
+ y = random.randint(int(0.75*medium_radius), int(1.25*medium_radius))
208
+ z = random.randint(int(0.75*medium_radius), int(1.25*medium_radius))
209
+ sigma = random.randint(3, 6)
210
+
211
+ geo = get_ellipsoid(x, y, z)
212
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
213
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
214
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
215
+ # texture = get_texture((4*x, 4*y, 4*z))
216
+ point = random_select(mask_scan)
217
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
218
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
219
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
220
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
221
+
222
+ # paste medium tumor geo into test sample
223
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
224
+ # texture_map[x_low:x_high, y_low:y_high, z_low:z_high] = texture
225
+
226
+ # large
227
+ num_tumor = random.randint(1,3)
228
+ for _ in range(num_tumor):
229
+ # Large tumor
230
+ x = random.randint(int(0.75*large_radius), int(1.25*large_radius))
231
+ y = random.randint(int(0.75*large_radius), int(1.25*large_radius))
232
+ z = random.randint(int(0.75*large_radius), int(1.25*large_radius))
233
+ sigma = random.randint(5, 10)
234
+ geo = get_ellipsoid(x, y, z)
235
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,1))
236
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(1,2))
237
+ geo = elasticdeform.deform_random_grid(geo, sigma=sigma, points=3, order=0, axis=(0,2))
238
+ # texture = get_texture((4*x, 4*y, 4*z))
239
+ point = random_select(mask_scan)
240
+ new_point = [point[0] + enlarge_x//2, point[1] + enlarge_y//2, point[2] + enlarge_z//2]
241
+ x_low, x_high = new_point[0] - geo.shape[0]//2, new_point[0] + geo.shape[0]//2
242
+ y_low, y_high = new_point[1] - geo.shape[1]//2, new_point[1] + geo.shape[1]//2
243
+ z_low, z_high = new_point[2] - geo.shape[2]//2, new_point[2] + geo.shape[2]//2
244
+
245
+ # paste small tumor geo into test sample
246
+ geo_mask[x_low:x_high, y_low:y_high, z_low:z_high] += geo
247
+ # texture_map[x_low:x_high, y_low:y_high, z_low:z_high] = texture
248
+
249
+ geo_mask = geo_mask[enlarge_x//2:-enlarge_x//2, enlarge_y//2:-enlarge_y//2, enlarge_z//2:-enlarge_z//2]
250
+ # texture_map = texture_map[enlarge_x//2:-enlarge_x//2, enlarge_y//2:-enlarge_y//2, enlarge_z//2:-enlarge_z//2]
251
+ geo_mask = (geo_mask * mask_scan) >=1
252
+
253
+ return geo_mask
254
+
255
+
256
+ def get_tumor(volume_scan, mask_scan, tumor_type):
257
+ tumor_mask = get_fixed_geo(mask_scan, tumor_type)
258
+
259
+ sigma = np.random.uniform(1, 2)
260
+ # difference = np.random.uniform(65, 145)
261
+ difference = 1
262
+
263
+ # blur the boundary
264
+ tumor_mask_blur = gaussian_filter(tumor_mask*1.0, sigma)
265
+
266
+
267
+ abnormally_full = volume_scan * (1 - mask_scan) + abnormally
268
+ abnormally_mask = mask_scan + geo_mask
269
+
270
+ return abnormally_full, abnormally_mask
271
+
272
+ def SynthesisTumor(volume_scan, mask_scan, tumor_type):
273
+ # for speed_generate_tumor, we only send the liver part into the generate program
274
+ x_start, x_end = np.where(np.any(mask_scan, axis=(1, 2)))[0][[0, -1]]
275
+ y_start, y_end = np.where(np.any(mask_scan, axis=(0, 2)))[0][[0, -1]]
276
+ z_start, z_end = np.where(np.any(mask_scan, axis=(0, 1)))[0][[0, -1]]
277
+
278
+ # shrink the boundary
279
+ x_start, x_end = max(0, x_start+1), min(mask_scan.shape[0], x_end-1)
280
+ y_start, y_end = max(0, y_start+1), min(mask_scan.shape[1], y_end-1)
281
+ z_start, z_end = max(0, z_start+1), min(mask_scan.shape[2], z_end-1)
282
+
283
+ ct_volume = volume_scan[x_start:x_end, y_start:y_end, z_start:z_end]
284
+ organ_mask = mask_scan[x_start:x_end, y_start:y_end, z_start:z_end]
285
+
286
+ # input texture shape: 420, 300, 320
287
+ # we need to cut it into the shape of liver_mask
288
+ # for examples, the liver_mask.shape = 286, 173, 46; we should change the texture shape
289
+ x_length, y_length, z_length = 64, 64, 64
290
+ crop_x = random.randint(x_start, x_end - x_length - 1) # random select the start point, -1 is to avoid boundary check
291
+ crop_y = random.randint(y_start, y_end - y_length - 1)
292
+ crop_z = random.randint(z_start, z_end - z_length - 1)
293
+
294
+ ct_volume, organ_tumor_mask = get_tumor(ct_volume, organ_mask, tumor_type)
295
+ volume_scan[x_start:x_end, y_start:y_end, z_start:z_end] = ct_volume
296
+ mask_scan[x_start:x_end, y_start:y_end, z_start:z_end] = organ_tumor_mask
297
+
298
+ return volume_scan, mask_scan
Generation_Pipeline_filter_all2/syn_pancreas/healthy_pancreas_1k.txt ADDED
@@ -0,0 +1,774 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BDMAP_00004652
2
+ BDMAP_00002164
3
+ BDMAP_00000439
4
+ BDMAP_00004775
5
+ BDMAP_00001148
6
+ BDMAP_00003384
7
+ BDMAP_00003634
8
+ BDMAP_00000030
9
+ BDMAP_00005119
10
+ BDMAP_00003580
11
+ BDMAP_00000320
12
+ BDMAP_00002185
13
+ BDMAP_00002487
14
+ BDMAP_00002775
15
+ BDMAP_00000159
16
+ BDMAP_00004475
17
+ BDMAP_00004278
18
+ BDMAP_00004131
19
+ BDMAP_00000244
20
+ BDMAP_00001966
21
+ BDMAP_00000939
22
+ BDMAP_00003928
23
+ BDMAP_00003031
24
+ BDMAP_00000568
25
+ BDMAP_00001309
26
+ BDMAP_00004232
27
+ BDMAP_00004431
28
+ BDMAP_00001794
29
+ BDMAP_00001752
30
+ BDMAP_00004228
31
+ BDMAP_00002363
32
+ BDMAP_00001020
33
+ BDMAP_00002739
34
+ BDMAP_00004462
35
+ BDMAP_00003749
36
+ BDMAP_00002472
37
+ BDMAP_00003455
38
+ BDMAP_00003911
39
+ BDMAP_00003486
40
+ BDMAP_00001496
41
+ BDMAP_00004378
42
+ BDMAP_00002282
43
+ BDMAP_00001343
44
+ BDMAP_00001747
45
+ BDMAP_00004450
46
+ BDMAP_00000607
47
+ BDMAP_00000100
48
+ BDMAP_00001620
49
+ BDMAP_00004415
50
+ BDMAP_00004897
51
+ BDMAP_00001737
52
+ BDMAP_00000604
53
+ BDMAP_00004922
54
+ BDMAP_00004870
55
+ BDMAP_00002060
56
+ BDMAP_00003412
57
+ BDMAP_00004850
58
+ BDMAP_00000794
59
+ BDMAP_00000989
60
+ BDMAP_00000205
61
+ BDMAP_00003151
62
+ BDMAP_00001255
63
+ BDMAP_00000667
64
+ BDMAP_00003343
65
+ BDMAP_00001237
66
+ BDMAP_00000023
67
+ BDMAP_00003281
68
+ BDMAP_00000907
69
+ BDMAP_00000432
70
+ BDMAP_00001782
71
+ BDMAP_00002166
72
+ BDMAP_00004481
73
+ BDMAP_00003363
74
+ BDMAP_00001474
75
+ BDMAP_00001995
76
+ BDMAP_00002854
77
+ BDMAP_00003603
78
+ BDMAP_00001383
79
+ BDMAP_00002656
80
+ BDMAP_00004427
81
+ BDMAP_00001563
82
+ BDMAP_00001809
83
+ BDMAP_00002114
84
+ BDMAP_00000304
85
+ BDMAP_00001692
86
+ BDMAP_00001688
87
+ BDMAP_00001119
88
+ BDMAP_00000449
89
+ BDMAP_00004014
90
+ BDMAP_00002524
91
+ BDMAP_00000725
92
+ BDMAP_00000918
93
+ BDMAP_00000642
94
+ BDMAP_00001238
95
+ BDMAP_00002373
96
+ BDMAP_00002326
97
+ BDMAP_00004373
98
+ BDMAP_00003615
99
+ BDMAP_00003324
100
+ BDMAP_00002654
101
+ BDMAP_00002849
102
+ BDMAP_00003491
103
+ BDMAP_00002655
104
+ BDMAP_00002712
105
+ BDMAP_00001516
106
+ BDMAP_00000469
107
+ BDMAP_00001549
108
+ BDMAP_00000713
109
+ BDMAP_00000745
110
+ BDMAP_00000259
111
+ BDMAP_00003569
112
+ BDMAP_00005067
113
+ BDMAP_00004185
114
+ BDMAP_00003357
115
+ BDMAP_00002419
116
+ BDMAP_00002598
117
+ BDMAP_00002167
118
+ BDMAP_00000137
119
+ BDMAP_00003448
120
+ BDMAP_00000965
121
+ BDMAP_00000232
122
+ BDMAP_00004608
123
+ BDMAP_00003680
124
+ BDMAP_00000716
125
+ BDMAP_00002403
126
+ BDMAP_00004216
127
+ BDMAP_00001359
128
+ BDMAP_00004175
129
+ BDMAP_00002791
130
+ BDMAP_00002940
131
+ BDMAP_00000355
132
+ BDMAP_00004294
133
+ BDMAP_00001426
134
+ BDMAP_00001475
135
+ BDMAP_00002986
136
+ BDMAP_00002884
137
+ BDMAP_00000400
138
+ BDMAP_00002410
139
+ BDMAP_00000297
140
+ BDMAP_00001636
141
+ BDMAP_00005113
142
+ BDMAP_00004074
143
+ BDMAP_00002333
144
+ BDMAP_00003976
145
+ BDMAP_00002383
146
+ BDMAP_00000161
147
+ BDMAP_00001212
148
+ BDMAP_00000366
149
+ BDMAP_00003070
150
+ BDMAP_00003943
151
+ BDMAP_00003930
152
+ BDMAP_00003164
153
+ BDMAP_00001906
154
+ BDMAP_00002889
155
+ BDMAP_00004163
156
+ BDMAP_00001456
157
+ BDMAP_00003972
158
+ BDMAP_00004586
159
+ BDMAP_00000626
160
+ BDMAP_00001095
161
+ BDMAP_00000532
162
+ BDMAP_00003377
163
+ BDMAP_00003225
164
+ BDMAP_00001289
165
+ BDMAP_00001275
166
+ BDMAP_00004509
167
+ BDMAP_00000998
168
+ BDMAP_00000836
169
+ BDMAP_00001015
170
+ BDMAP_00004650
171
+ BDMAP_00005186
172
+ BDMAP_00000608
173
+ BDMAP_00003898
174
+ BDMAP_00002696
175
+ BDMAP_00003560
176
+ BDMAP_00004578
177
+ BDMAP_00000828
178
+ BDMAP_00000690
179
+ BDMAP_00003564
180
+ BDMAP_00005174
181
+ BDMAP_00000132
182
+ BDMAP_00005105
183
+ BDMAP_00000902
184
+ BDMAP_00003947
185
+ BDMAP_00002184
186
+ BDMAP_00001785
187
+ BDMAP_00002361
188
+ BDMAP_00003255
189
+ BDMAP_00000971
190
+ BDMAP_00003493
191
+ BDMAP_00002267
192
+ BDMAP_00005154
193
+ BDMAP_00000982
194
+ BDMAP_00005157
195
+ BDMAP_00004384
196
+ BDMAP_00003063
197
+ BDMAP_00001982
198
+ BDMAP_00002273
199
+ BDMAP_00001102
200
+ BDMAP_00002689
201
+ BDMAP_00000034
202
+ BDMAP_00001514
203
+ BDMAP_00005081
204
+ BDMAP_00001786
205
+ BDMAP_00004033
206
+ BDMAP_00004457
207
+ BDMAP_00000710
208
+ BDMAP_00001198
209
+ BDMAP_00004479
210
+ BDMAP_00000873
211
+ BDMAP_00000362
212
+ BDMAP_00004616
213
+ BDMAP_00003128
214
+ BDMAP_00001607
215
+ BDMAP_00004104
216
+ BDMAP_00001517
217
+ BDMAP_00004639
218
+ BDMAP_00005170
219
+ BDMAP_00002305
220
+ BDMAP_00004746
221
+ BDMAP_00003333
222
+ BDMAP_00001807
223
+ BDMAP_00004579
224
+ BDMAP_00002260
225
+ BDMAP_00004416
226
+ BDMAP_00003932
227
+ BDMAP_00001316
228
+ BDMAP_00003411
229
+ BDMAP_00000839
230
+ BDMAP_00004738
231
+ BDMAP_00001438
232
+ BDMAP_00003435
233
+ BDMAP_00001697
234
+ BDMAP_00001911
235
+ BDMAP_00001735
236
+ BDMAP_00002902
237
+ BDMAP_00001834
238
+ BDMAP_00000069
239
+ BDMAP_00004066
240
+ BDMAP_00000434
241
+ BDMAP_00004744
242
+ BDMAP_00000347
243
+ BDMAP_00001246
244
+ BDMAP_00003150
245
+ BDMAP_00003957
246
+ BDMAP_00001768
247
+ BDMAP_00002663
248
+ BDMAP_00004147
249
+ BDMAP_00003510
250
+ BDMAP_00002242
251
+ BDMAP_00005016
252
+ BDMAP_00002275
253
+ BDMAP_00001924
254
+ BDMAP_00002214
255
+ BDMAP_00002529
256
+ BDMAP_00000562
257
+ BDMAP_00000122
258
+ BDMAP_00002707
259
+ BDMAP_00000874
260
+ BDMAP_00000176
261
+ BDMAP_00002804
262
+ BDMAP_00005005
263
+ BDMAP_00001422
264
+ BDMAP_00005017
265
+ BDMAP_00000653
266
+ BDMAP_00002609
267
+ BDMAP_00003327
268
+ BDMAP_00002484
269
+ BDMAP_00004673
270
+ BDMAP_00004493
271
+ BDMAP_00003740
272
+ BDMAP_00002271
273
+ BDMAP_00002742
274
+ BDMAP_00002826
275
+ BDMAP_00001035
276
+ BDMAP_00002068
277
+ BDMAP_00003815
278
+ BDMAP_00003052
279
+ BDMAP_00004499
280
+ BDMAP_00002065
281
+ BDMAP_00001025
282
+ BDMAP_00004888
283
+ BDMAP_00002592
284
+ BDMAP_00004030
285
+ BDMAP_00001024
286
+ BDMAP_00002041
287
+ BDMAP_00002807
288
+ BDMAP_00002751
289
+ BDMAP_00003272
290
+ BDMAP_00004600
291
+ BDMAP_00004154
292
+ BDMAP_00003774
293
+ BDMAP_00000948
294
+ BDMAP_00002173
295
+ BDMAP_00004510
296
+ BDMAP_00000104
297
+ BDMAP_00004374
298
+ BDMAP_00000429
299
+ BDMAP_00004420
300
+ BDMAP_00001853
301
+ BDMAP_00003600
302
+ BDMAP_00002349
303
+ BDMAP_00001863
304
+ BDMAP_00004830
305
+ BDMAP_00002981
306
+ BDMAP_00001941
307
+ BDMAP_00001128
308
+ BDMAP_00005151
309
+ BDMAP_00003890
310
+ BDMAP_00003640
311
+ BDMAP_00004257
312
+ BDMAP_00004943
313
+ BDMAP_00001068
314
+ BDMAP_00001305
315
+ BDMAP_00000414
316
+ BDMAP_00000465
317
+ BDMAP_00003727
318
+ BDMAP_00002199
319
+ BDMAP_00001769
320
+ BDMAP_00004187
321
+ BDMAP_00001891
322
+ BDMAP_00000980
323
+ BDMAP_00003923
324
+ BDMAP_00000942
325
+ BDMAP_00001114
326
+ BDMAP_00001602
327
+ BDMAP_00002845
328
+ BDMAP_00003178
329
+ BDMAP_00003409
330
+ BDMAP_00001562
331
+ BDMAP_00002909
332
+ BDMAP_00003808
333
+ BDMAP_00001169
334
+ BDMAP_00001104
335
+ BDMAP_00001483
336
+ BDMAP_00005009
337
+ BDMAP_00001957
338
+ BDMAP_00003153
339
+ BDMAP_00001444
340
+ BDMAP_00000851
341
+ BDMAP_00005191
342
+ BDMAP_00000687
343
+ BDMAP_00003722
344
+ BDMAP_00003330
345
+ BDMAP_00002347
346
+ BDMAP_00002955
347
+ BDMAP_00001089
348
+ BDMAP_00004529
349
+ BDMAP_00003268
350
+ BDMAP_00001522
351
+ BDMAP_00001502
352
+ BDMAP_00000240
353
+ BDMAP_00004867
354
+ BDMAP_00000480
355
+ BDMAP_00000452
356
+ BDMAP_00002918
357
+ BDMAP_00002953
358
+ BDMAP_00002039
359
+ BDMAP_00000889
360
+ BDMAP_00002746
361
+ BDMAP_00003608
362
+ BDMAP_00003664
363
+ BDMAP_00003299
364
+ BDMAP_00001445
365
+ BDMAP_00000113
366
+ BDMAP_00001705
367
+ BDMAP_00000044
368
+ BDMAP_00003513
369
+ BDMAP_00001261
370
+ BDMAP_00004990
371
+ BDMAP_00003143
372
+ BDMAP_00003111
373
+ BDMAP_00002319
374
+ BDMAP_00004664
375
+ BDMAP_00003717
376
+ BDMAP_00004717
377
+ BDMAP_00004745
378
+ BDMAP_00000671
379
+ BDMAP_00002990
380
+ BDMAP_00004901
381
+ BDMAP_00002545
382
+ BDMAP_00004980
383
+ BDMAP_00000913
384
+ BDMAP_00000437
385
+ BDMAP_00002864
386
+ BDMAP_00000364
387
+ BDMAP_00004195
388
+ BDMAP_00000162
389
+ BDMAP_00002840
390
+ BDMAP_00000233
391
+ BDMAP_00002744
392
+ BDMAP_00001218
393
+ BDMAP_00002289
394
+ BDMAP_00000229
395
+ BDMAP_00005114
396
+ BDMAP_00000279
397
+ BDMAP_00003832
398
+ BDMAP_00000241
399
+ BDMAP_00002251
400
+ BDMAP_00001676
401
+ BDMAP_00001635
402
+ BDMAP_00003444
403
+ BDMAP_00002265
404
+ BDMAP_00002498
405
+ BDMAP_00001209
406
+ BDMAP_00001138
407
+ BDMAP_00002407
408
+ BDMAP_00003798
409
+ BDMAP_00001325
410
+ BDMAP_00002631
411
+ BDMAP_00004304
412
+ BDMAP_00001078
413
+ BDMAP_00002562
414
+ BDMAP_00003576
415
+ BDMAP_00001977
416
+ BDMAP_00002396
417
+ BDMAP_00001333
418
+ BDMAP_00004925
419
+ BDMAP_00004903
420
+ BDMAP_00000273
421
+ BDMAP_00000571
422
+ BDMAP_00001027
423
+ BDMAP_00000149
424
+ BDMAP_00001962
425
+ BDMAP_00003481
426
+ BDMAP_00001256
427
+ BDMAP_00000871
428
+ BDMAP_00000926
429
+ BDMAP_00000572
430
+ BDMAP_00004558
431
+ BDMAP_00000435
432
+ BDMAP_00000837
433
+ BDMAP_00003713
434
+ BDMAP_00002875
435
+ BDMAP_00004645
436
+ BDMAP_00001711
437
+ BDMAP_00001296
438
+ BDMAP_00002648
439
+ BDMAP_00004561
440
+ BDMAP_00002318
441
+ BDMAP_00001835
442
+ BDMAP_00003524
443
+ BDMAP_00002959
444
+ BDMAP_00002422
445
+ BDMAP_00004597
446
+ BDMAP_00000487
447
+ BDMAP_00002359
448
+ BDMAP_00005001
449
+ BDMAP_00004817
450
+ BDMAP_00001539
451
+ BDMAP_00002936
452
+ BDMAP_00002719
453
+ BDMAP_00005167
454
+ BDMAP_00001265
455
+ BDMAP_00001471
456
+ BDMAP_00001511
457
+ BDMAP_00005139
458
+ BDMAP_00002426
459
+ BDMAP_00002288
460
+ BDMAP_00004808
461
+ BDMAP_00002085
462
+ BDMAP_00004435
463
+ BDMAP_00000319
464
+ BDMAP_00003614
465
+ BDMAP_00001109
466
+ BDMAP_00000331
467
+ BDMAP_00004491
468
+ BDMAP_00002440
469
+ BDMAP_00003373
470
+ BDMAP_00005065
471
+ BDMAP_00005006
472
+ BDMAP_00002509
473
+ BDMAP_00003973
474
+ BDMAP_00004417
475
+ BDMAP_00000935
476
+ BDMAP_00004624
477
+ BDMAP_00003364
478
+ BDMAP_00005085
479
+ BDMAP_00003073
480
+ BDMAP_00002730
481
+ BDMAP_00004825
482
+ BDMAP_00000039
483
+ BDMAP_00004615
484
+ BDMAP_00003736
485
+ BDMAP_00005097
486
+ BDMAP_00003074
487
+ BDMAP_00000662
488
+ BDMAP_00001122
489
+ BDMAP_00002252
490
+ BDMAP_00001396
491
+ BDMAP_00004011
492
+ BDMAP_00004981
493
+ BDMAP_00004165
494
+ BDMAP_00003920
495
+ BDMAP_00001215
496
+ BDMAP_00003867
497
+ BDMAP_00000923
498
+ BDMAP_00002626
499
+ BDMAP_00003315
500
+ BDMAP_00000660
501
+ BDMAP_00000329
502
+ BDMAP_00004508
503
+ BDMAP_00001518
504
+ BDMAP_00003849
505
+ BDMAP_00003897
506
+ BDMAP_00003300
507
+ BDMAP_00002253
508
+ BDMAP_00003514
509
+ BDMAP_00000117
510
+ BDMAP_00002421
511
+ BDMAP_00001413
512
+ BDMAP_00004328
513
+ BDMAP_00001130
514
+ BDMAP_00000043
515
+ BDMAP_00001410
516
+ BDMAP_00000245
517
+ BDMAP_00004117
518
+ BDMAP_00002401
519
+ BDMAP_00003857
520
+ BDMAP_00000921
521
+ BDMAP_00000138
522
+ BDMAP_00003113
523
+ BDMAP_00003358
524
+ BDMAP_00002099
525
+ BDMAP_00004016
526
+ BDMAP_00003439
527
+ BDMAP_00002152
528
+ BDMAP_00003767
529
+ BDMAP_00001598
530
+ BDMAP_00003482
531
+ BDMAP_00003520
532
+ BDMAP_00002075
533
+ BDMAP_00000987
534
+ BDMAP_00003946
535
+ BDMAP_00005160
536
+ BDMAP_00001286
537
+ BDMAP_00003359
538
+ BDMAP_00002661
539
+ BDMAP_00004704
540
+ BDMAP_00003994
541
+ BDMAP_00002226
542
+ BDMAP_00000968
543
+ BDMAP_00003556
544
+ BDMAP_00003236
545
+ BDMAP_00001791
546
+ BDMAP_00004712
547
+ BDMAP_00001077
548
+ BDMAP_00003955
549
+ BDMAP_00002479
550
+ BDMAP_00001865
551
+ BDMAP_00001059
552
+ BDMAP_00002704
553
+ BDMAP_00000656
554
+ BDMAP_00001379
555
+ BDMAP_00000883
556
+ BDMAP_00002856
557
+ BDMAP_00004199
558
+ BDMAP_00001200
559
+ BDMAP_00005083
560
+ BDMAP_00004552
561
+ BDMAP_00000616
562
+ BDMAP_00004834
563
+ BDMAP_00004815
564
+ BDMAP_00001826
565
+ BDMAP_00000615
566
+ BDMAP_00001045
567
+ BDMAP_00002695
568
+ BDMAP_00004017
569
+ BDMAP_00002103
570
+ BDMAP_00002057
571
+ BDMAP_00004620
572
+ BDMAP_00000128
573
+ BDMAP_00001185
574
+ BDMAP_00002612
575
+ BDMAP_00005073
576
+ BDMAP_00001753
577
+ BDMAP_00004196
578
+ BDMAP_00004281
579
+ BDMAP_00002717
580
+ BDMAP_00000263
581
+ BDMAP_00004103
582
+ BDMAP_00003381
583
+ BDMAP_00001093
584
+ BDMAP_00000373
585
+ BDMAP_00000881
586
+ BDMAP_00002230
587
+ BDMAP_00001707
588
+ BDMAP_00002476
589
+ BDMAP_00003294
590
+ BDMAP_00004482
591
+ BDMAP_00003267
592
+ BDMAP_00002710
593
+ BDMAP_00002451
594
+ BDMAP_00001270
595
+ BDMAP_00004878
596
+ BDMAP_00001784
597
+ BDMAP_00001281
598
+ BDMAP_00002283
599
+ BDMAP_00001183
600
+ BDMAP_00001945
601
+ BDMAP_00004604
602
+ BDMAP_00000413
603
+ BDMAP_00003506
604
+ BDMAP_00002458
605
+ BDMAP_00000977
606
+ BDMAP_00000833
607
+ BDMAP_00001055
608
+ BDMAP_00002495
609
+ BDMAP_00000887
610
+ BDMAP_00002496
611
+ BDMAP_00002942
612
+ BDMAP_00000574
613
+ BDMAP_00001868
614
+ BDMAP_00000547
615
+ BDMAP_00001230
616
+ BDMAP_00003762
617
+ BDMAP_00003971
618
+ BDMAP_00000321
619
+ BDMAP_00004876
620
+ BDMAP_00003833
621
+ BDMAP_00003461
622
+ BDMAP_00003301
623
+ BDMAP_00002846
624
+ BDMAP_00002582
625
+ BDMAP_00001710
626
+ BDMAP_00001487
627
+ BDMAP_00000936
628
+ BDMAP_00004121
629
+ BDMAP_00004459
630
+ BDMAP_00000219
631
+ BDMAP_00000091
632
+ BDMAP_00001283
633
+ BDMAP_00000084
634
+ BDMAP_00000516
635
+ BDMAP_00004250
636
+ BDMAP_00001732
637
+ BDMAP_00003694
638
+ BDMAP_00004031
639
+ BDMAP_00001557
640
+ BDMAP_00002437
641
+ BDMAP_00002933
642
+ BDMAP_00000264
643
+ BDMAP_00005099
644
+ BDMAP_00004296
645
+ BDMAP_00001917
646
+ BDMAP_00003252
647
+ BDMAP_00004389
648
+ BDMAP_00002463
649
+ BDMAP_00004253
650
+ BDMAP_00004910
651
+ BDMAP_00003172
652
+ BDMAP_00001624
653
+ BDMAP_00003484
654
+ BDMAP_00001907
655
+ BDMAP_00003952
656
+ BDMAP_00002653
657
+ BDMAP_00000368
658
+ BDMAP_00000569
659
+ BDMAP_00004995
660
+ BDMAP_00003956
661
+ BDMAP_00003497
662
+ BDMAP_00003058
663
+ BDMAP_00000552
664
+ BDMAP_00000481
665
+ BDMAP_00000805
666
+ BDMAP_00003002
667
+ BDMAP_00000698
668
+ BDMAP_00004783
669
+ BDMAP_00001324
670
+ BDMAP_00002133
671
+ BDMAP_00005120
672
+ BDMAP_00003581
673
+ BDMAP_00004890
674
+ BDMAP_00001533
675
+ BDMAP_00004039
676
+ BDMAP_00000190
677
+ BDMAP_00004028
678
+ BDMAP_00004130
679
+ BDMAP_00001370
680
+ BDMAP_00002805
681
+ BDMAP_00001397
682
+ BDMAP_00001126
683
+ BDMAP_00001875
684
+ BDMAP_00005130
685
+ BDMAP_00003361
686
+ BDMAP_00002485
687
+ BDMAP_00001273
688
+ BDMAP_00000582
689
+ BDMAP_00003672
690
+ BDMAP_00000778
691
+ BDMAP_00002841
692
+ BDMAP_00001242
693
+ BDMAP_00000345
694
+ BDMAP_00000036
695
+ BDMAP_00003996
696
+ BDMAP_00003701
697
+ BDMAP_00003425
698
+ BDMAP_00001656
699
+ BDMAP_00001802
700
+ BDMAP_00001420
701
+ BDMAP_00003752
702
+ BDMAP_00002924
703
+ BDMAP_00003202
704
+ BDMAP_00000831
705
+ BDMAP_00003392
706
+ BDMAP_00002022
707
+ BDMAP_00001223
708
+ BDMAP_00003457
709
+ BDMAP_00001236
710
+ BDMAP_00000810
711
+ BDMAP_00004676
712
+ BDMAP_00003847
713
+ BDMAP_00001225
714
+ BDMAP_00005168
715
+ BDMAP_00004113
716
+ BDMAP_00002828
717
+ BDMAP_00004087
718
+ BDMAP_00004407
719
+ BDMAP_00002748
720
+ BDMAP_00003516
721
+ BDMAP_00004395
722
+ BDMAP_00001985
723
+ BDMAP_00001171
724
+ BDMAP_00000101
725
+ BDMAP_00002117
726
+ BDMAP_00001434
727
+ BDMAP_00000139
728
+ BDMAP_00002465
729
+ BDMAP_00001251
730
+ BDMAP_00001908
731
+ BDMAP_00002354
732
+ BDMAP_00002776
733
+ BDMAP_00004887
734
+ BDMAP_00000066
735
+ BDMAP_00003549
736
+ BDMAP_00000812
737
+ BDMAP_00000353
738
+ BDMAP_00004894
739
+ BDMAP_00004956
740
+ BDMAP_00002871
741
+ BDMAP_00004764
742
+ BDMAP_00004551
743
+ BDMAP_00002404
744
+ BDMAP_00000059
745
+ BDMAP_00002017
746
+ BDMAP_00003558
747
+ BDMAP_00004065
748
+ BDMAP_00003406
749
+ BDMAP_00002471
750
+ BDMAP_00000941
751
+ BDMAP_00003109
752
+ BDMAP_00000511
753
+ BDMAP_00000826
754
+ BDMAP_00004839
755
+ BDMAP_00004671
756
+ BDMAP_00002930
757
+ BDMAP_00004331
758
+ BDMAP_00001664
759
+ BDMAP_00001001
760
+ BDMAP_00001766
761
+ BDMAP_00003827
762
+ BDMAP_00001258
763
+ BDMAP_00001892
764
+ BDMAP_00000062
765
+ BDMAP_00000867
766
+ BDMAP_00002803
767
+ BDMAP_00000285
768
+ BDMAP_00001647
769
+ BDMAP_00005077
770
+ BDMAP_00000152
771
+ BDMAP_00000709
772
+ BDMAP_00002172
773
+ BDMAP_00004148
774
+ BDMAP_00001010
Generation_Pipeline_filter_all2/syn_pancreas/requirements.txt ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==1.1.0
2
+ accelerate==0.11.0
3
+ aiohttp==3.8.1
4
+ aiosignal==1.2.0
5
+ antlr4-python3-runtime==4.9.3
6
+ async-timeout==4.0.2
7
+ attrs==21.4.0
8
+ autopep8==1.6.0
9
+ cachetools==5.2.0
10
+ certifi==2022.6.15
11
+ charset-normalizer==2.0.12
12
+ click==8.1.3
13
+ cycler==0.11.0
14
+ Deprecated==1.2.13
15
+ docker-pycreds==0.4.0
16
+ einops==0.4.1
17
+ einops-exts==0.0.3
18
+ ema-pytorch==0.0.8
19
+ fonttools==4.34.4
20
+ frozenlist==1.3.0
21
+ fsspec==2022.5.0
22
+ ftfy==6.1.1
23
+ future==0.18.2
24
+ gitdb==4.0.9
25
+ GitPython==3.1.27
26
+ google-auth==2.9.0
27
+ google-auth-oauthlib==0.4.6
28
+ grpcio==1.47.0
29
+ h5py==3.7.0
30
+ humanize==4.2.2
31
+ hydra-core==1.2.0
32
+ idna==3.3
33
+ imageio==2.19.3
34
+ imageio-ffmpeg==0.4.7
35
+ importlib-metadata==4.12.0
36
+ importlib-resources==5.9.0
37
+ joblib==1.1.0
38
+ kiwisolver==1.4.3
39
+ lxml==4.9.1
40
+ Markdown==3.3.7
41
+ matplotlib==3.5.2
42
+ multidict==6.0.2
43
+ networkx==2.8.5
44
+ nibabel==4.0.1
45
+ nilearn==0.9.1
46
+ numpy==1.23.0
47
+ oauthlib==3.2.0
48
+ omegaconf==2.2.3
49
+ pandas==1.4.3
50
+ Pillow==9.1.1
51
+ pyasn1==0.4.8
52
+ pyasn1-modules==0.2.8
53
+ pycodestyle==2.8.0
54
+ pyDeprecate==0.3.1
55
+ pydicom==2.3.0
56
+ pytorch-lightning==1.6.4
57
+ pytz==2022.1
58
+ PyWavelets==1.3.0
59
+ PyYAML==6.0
60
+ pyzmq==19.0.2
61
+ regex==2022.6.2
62
+ requests==2.28.0
63
+ requests-oauthlib==1.3.1
64
+ rotary-embedding-torch==0.1.5
65
+ rsa==4.8
66
+ scikit-image==0.19.3
67
+ scikit-learn==1.1.2
68
+ scikit-video==1.1.11
69
+ scipy==1.8.1
70
+ seaborn==0.11.2
71
+ sentry-sdk==1.7.2
72
+ setproctitle==1.2.3
73
+ shortuuid==1.0.9
74
+ SimpleITK==2.1.1.2
75
+ smmap==5.0.0
76
+ tensorboard==2.9.1
77
+ tensorboard-data-server==0.6.1
78
+ tensorboard-plugin-wit==1.8.1
79
+ threadpoolctl==3.1.0
80
+ tifffile==2022.8.3
81
+ toml==0.10.2
82
+ torch-tb-profiler==0.4.0
83
+ torchio==0.18.80
84
+ torchmetrics==0.9.1
85
+ tqdm==4.64.0
86
+ typing_extensions==4.2.0
87
+ urllib3==1.26.9
88
+ wandb==0.12.21
89
+ Werkzeug==2.1.2
90
+ wrapt==1.14.1
91
+ yarl==1.7.2
92
+ zipp==3.8.0
93
+ wandb
94
+ tensorboardX==2.4.1
Generation_Pipeline_filter_all2/val_set/bodymap_colon.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BDMAP_00004910
2
+ BDMAP_00001438
3
+ BDMAP_00000568
4
+ BDMAP_00002828
5
+ BDMAP_00003634
6
+ BDMAP_00004121
7
+ BDMAP_00004764
8
+ BDMAP_00003972
9
+ BDMAP_00003113
10
+ BDMAP_00005001
11
+ BDMAP_00001785
12
+ BDMAP_00005016
13
+ BDMAP_00002739
14
+ BDMAP_00003299
15
+ BDMAP_00003357
16
+ BDMAP_00001078
17
+ BDMAP_00000874
18
+ BDMAP_00003560
19
+ BDMAP_00003373
20
+ BDMAP_00003172
21
+ BDMAP_00002875
22
+ BDMAP_00000552
23
+ BDMAP_00003510
24
+ BDMAP_00004604
25
+ BDMAP_00002598
Generation_Pipeline_filter_all2/val_set/bodymap_kidney.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BDMAP_00000487
2
+ BDMAP_00002631
3
+ BDMAP_00002744
4
+ BDMAP_00000833
5
+ BDMAP_00002648
6
+ BDMAP_00002840
7
+ BDMAP_00000608
8
+ BDMAP_00002804
9
+ BDMAP_00002775
10
+ BDMAP_00004551
11
+ BDMAP_00001413
12
+ BDMAP_00000511
13
+ BDMAP_00003150
14
+ BDMAP_00000794
15
+ BDMAP_00001255
16
+ BDMAP_00002242
17
+ BDMAP_00004746
18
+ BDMAP_00002864
19
+ BDMAP_00003486
20
+ BDMAP_00004250
21
+ BDMAP_00003143
22
+ BDMAP_00003164
23
+ BDMAP_00004578
24
+ BDMAP_00001735
Generation_Pipeline_filter_all2/val_set/bodymap_liver.txt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BDMAP_00004281
2
+ BDMAP_00003481
3
+ BDMAP_00004890
4
+ BDMAP_00001786
5
+ BDMAP_00000101
6
+ BDMAP_00004117
7
+ BDMAP_00000615
8
+ BDMAP_00000921
9
+ BDMAP_00005130
10
+ BDMAP_00004378
11
+ BDMAP_00004704
12
+ BDMAP_00003439
13
+ BDMAP_00002717
14
+ BDMAP_00004878
15
+ BDMAP_00000100
16
+ BDMAP_00001309
17
+ BDMAP_00002214
18
+ BDMAP_00001198
19
+ BDMAP_00001962
20
+ BDMAP_00002463
21
+ BDMAP_00005139
22
+ BDMAP_00000831
23
+ BDMAP_00002955
24
+ BDMAP_00003272
25
+ BDMAP_00000745
Generation_Pipeline_filter_all2/val_set/bodymap_pancreas.txt ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BDMAP_00000332
2
+ BDMAP_00004858
3
+ BDMAP_00005155
4
+ BDMAP_00001205
5
+ BDMAP_00004770
6
+ BDMAP_00001361
7
+ BDMAP_00002944
8
+ BDMAP_00003961
9
+ BDMAP_00000430
10
+ BDMAP_00000679
11
+ BDMAP_00003809
12
+ BDMAP_00004115
13
+ BDMAP_00003367
14
+ BDMAP_00002899
15
+ BDMAP_00003771
16
+ BDMAP_00003502
17
+ BDMAP_00001628
18
+ BDMAP_00003884
19
+ BDMAP_00005074
20
+ BDMAP_00003114
21
+ BDMAP_00004741
22
+ BDMAP_00001746
23
+ BDMAP_00002603
24
+ BDMAP_00004128