Diff of /args.py [000000] .. [408896]

Switch to unified view

a b/args.py
1
import argparse
2
import shutil
3
import pickle
4
import copy
5
import os
6
import numpy as np
7
8
9
class BaseArgParser(object):
10
    def __init__(self):
11
        self.parser = argparse.ArgumentParser()
12
13
    def namespace_to_dict(self, args):
14
        """Turns a nested Namespace object to a nested dictionary"""
15
        args_dict = vars(copy.deepcopy(args))
16
17
        for arg in args_dict:
18
            obj = args_dict[arg]
19
            if isinstance(obj, argparse.Namespace):
20
                args_dict[arg] = self.namespace_to_dict(obj)
21
22
        return args_dict
23
24
    def fix_nested_namespaces(self, args):
25
        """Makes sure that nested Namespace work. Supports only one level of nesting."""
26
        group_name_keys = []
27
28
        for key in args.__dict__:
29
            if '.' in key:
30
                group, name = key.split('.')
31
                group_name_keys.append((group, name, key))
32
33
        for group, name, key in group_name_keys:
34
            if group not in args:
35
                args.__dict__[group] = argparse.Namespace()
36
37
            args.__dict__[group].__dict__[name] = args.__dict__[key]
38
            del args.__dict__[key]
39
40
    def parse_args(self):
41
        args = self.parser.parse_args()
42
        args = self.namespace_to_dict(args)
43
        self.fix_nested_namespaces(args)
44
        return args
45
46
47
class PreproArgParser(BaseArgParser):
48
    def __init__(self):
49
        super(PreproArgParser, self).__init__()
50
51
        self.parser.add_argument('--in_locs', type=str, required=True,
52
                help='Comma-separated list of paths to all data folders.')
53
        self.parser.add_argument('--modalities', type=str, required=True,
54
                help='Comma-separated list of all input modalities to use.')
55
        self.parser.add_argument('--truth', type=str, required=True,
56
                help='Truth label pattern to use.')
57
58
        self.parser.add_argument('--create_val', action='store_true', default=False,
59
                help='Whether to create validation set.')
60
        self.parser.add_argument('--out_loc', type=str, default='./data',
61
                help='Location to write preprocessed data.')
62
63
    def parse_args(self):
64
        args = self.parser.parse_args()
65
66
        # Create list of all input datasets.
67
        args.in_locs = args.in_locs.split(',')
68
69
        # Create list of all accepted modalities.
70
        args.modalities = args.modalities.split(',')
71
72
        # Create output directory if it doesn't already exist.
73
        if os.path.isdir(args.out_loc):
74
            shutil.rmtree(args.out_loc)
75
76
        args.train_loc = os.path.join(args.out_loc, 'train')
77
        args.val_loc = os.path.join(args.out_loc, 'val')
78
79
        os.mkdir(args.out_loc)
80
        os.mkdir(args.train_loc)
81
        os.mkdir(args.val_loc)
82
83
        return args
84
85
86
class TrainArgParser(BaseArgParser):
87
    def __init__(self):
88
        super(TrainArgParser, self).__init__()
89
90
        # Data args.
91
        self.parser.add_argument('--train_loc', type=str, required=True,
92
                help='Location of .tfrecords training data.')
93
        self.parser.add_argument('--prepro_loc', type=str, required=True,
94
                help='Location of preprocessed dump.')
95
        self.parser.add_argument('--val_loc', type=str, default='',
96
                help='Location of .tfrecords validation data.')
97
98
        # Checkpoint args.
99
        self.parser.add_argument('--save_folder', type=str, default='',
100
                help='Output folder to save checkpoints, logs, and configs.')
101
        self.parser.add_argument('--load_folder', type=str, default='',
102
                help='Input folder to load checkpoints and configs to resume training.')
103
104
        # Training args.
105
        self.parser.add_argument('--lr', type=float, default=1e-4,
106
                help='Initial learning rate for training.')
107
        self.parser.add_argument('--batch_size', type=int, default=1,
108
                help='Batch size to use in training.')
109
        self.parser.add_argument('--patience', type=int, default=-1,
110
                help='Number of epochs without validation improvement to stop training.')
111
        self.parser.add_argument('--n_epochs', type=int, default=300,
112
                help='Number of epochs to train for.')
113
        self.parser.add_argument('--gpu', action='store_true', default=False,
114
                help='Whether to train using GPU.')
115
116
        # Augmentation args.
117
        self.parser.add_argument('--crop_size', type=str, default='128,128,128',
118
                help='Crop size of image (comma-separated h,w,d).')
119
120
        # Model args.
121
        self.parser.add_argument('--data_format', type=str, dest='model_args.data_format',
122
                default='channels_first', choices=['channels_last', 'channels_first'],
123
                help='Data format to be passed through the model.')
124
        self.parser.add_argument('--base_filters', type=int, dest='model_args.base_filters', default=32,
125
                help='Number of filters in the base convolutional layer.')
126
        self.parser.add_argument('--depth', type=int, dest='model_args.depth', default=4,
127
                help='Number of spatial levels through the model.')
128
        self.parser.add_argument('--l2_scale', type=float, dest='model_args.l2_scale', default=1e-5,
129
                help='Scale of L2 regularization applied to all kernels.')
130
        self.parser.add_argument('--dropout', type=float, dest='model_args.dropout', default=0.2,
131
                help='Dropout ratio to apply to input data.')
132
        self.parser.add_argument('--groups', type=int, dest='model_args.groups', default=8,
133
                help='Number of groups in group normalization.')
134
        self.parser.add_argument('--reduction', type=int, dest='model_args.reduction', default=8,
135
                help='Size of reduction ratio in squeeze-excitation layers.')
136
        self.parser.add_argument('--downsampling', type=str, dest='model_args.downsampling',
137
                default='conv', choices=['conv', 'max', 'avg'],
138
                help='Type of downsampling method.')
139
        self.parser.add_argument('--upsampling', type=str, dest='model_args.upsampling',
140
                default='conv', choices=['conv', 'linear'],
141
                help='Type of upsampling method.')
142
        self.parser.add_argument('--out_ch', type=int, dest='model_args.out_ch', default=3,
143
                help='Number of output classes.')
144
145
    def parse_args(self):
146
        args = self.parser.parse_args()
147
148
        # Fix nested Namespaces.
149
        self.fix_nested_namespaces(args)
150
        args.data_format = args.model_args.data_format
151
152
        # Check data format and GPU compatibility.
153
        args.device = '/device:GPU:0' if args.gpu else '/cpu:0'
154
        if not args.gpu:
155
            assert args.model_args.data_format == 'channels_last', \
156
                'tf.keras.layers.Conv3D only supports `channels_last` input for CPU.'
157
158
        # Convert model args to dictionaries.
159
        args.model_args = self.namespace_to_dict(args.model_args)
160
161
        # Set crop size.
162
        args.crop_size = args.crop_size.split(',')
163
        args.crop_size = [int(s) for s in args.crop_size]
164
165
        # Load preprocessed stats.
166
        prepro = np.load(args.prepro_loc).item()
167
        args.prepro_size = [prepro['size']['h'], prepro['size']['w'], prepro['size']['d'], prepro['size']['c']]
168
169
        # Check that sizes work out.
170
        assert (args.model_args['base_filters'] / 2) % args.model_args['groups'] == 0, \
171
            'Base filters must be a multiple of {} for group normalization at lowest spatial level.'.format(args.model_args['groups'] * 2)
172
173
        assert args.model_args['base_filters'] % args.model_args['reduction'] == 0, \
174
            'Base filters must be a multiple of {} for squeeze-excitation reduction.'.format(args.model_args['reduction'])
175
176
        # Add args.model_args.in_ch for output size of variational autoencoder.
177
        args.model_args['in_ch'] = prepro['size']['c']
178
179
        # Check for checkpointing option.
180
        if args.load_folder:
181
            with open(os.path.join(args.load_folder, 'train_args.pkl'), 'rb') as f:
182
                chkpt_args = pickle.load(f)
183
                args.model_args = chkpt_args['model_args']
184
                args.crop_size = chkpt_args.crop_size
185
                assert isinstance(args.model_args, dict)
186
            args.save_folder = args.load_folder
187
188
        # Create checkpoint folder if necessary.
189
        if not os.path.isdir(args.save_folder):
190
            os.mkdir(args.save_folder)
191
192
        # Save training args.
193
        with open(os.path.join(args.save_folder, 'train_args.pkl'), 'wb') as f:
194
            pickle.dump(self.namespace_to_dict(args), f)
195
        
196
        return args
197
198
199
class TestArgParser(BaseArgParser):
200
    def __init__(self):
201
        super(TestArgParser, self).__init__()
202
203
        # Data.
204
        self.parser.add_argument('--in_locs', type=str, required=True,
205
                help='Comma-separated paths of test data.')
206
        self.parser.add_argument('--modalities', type=str, required=True,
207
                help='Comma-separated modalities to be used as input')
208
        self.parser.add_argument('--truth', type=str, default='',
209
                help='Truth label pattern to use (optional).')
210
211
        # Training and preprocessing stats.
212
        self.parser.add_argument('--tumor_prepro', type=str, required=True,
213
                help='Path to Numpy preprocessing dump for tumor segmentation.')
214
        self.parser.add_argument('--skull_prepro', type=str, default='',
215
                help='Path to Numpy preprocessing dump for skull segmentation.')
216
        self.parser.add_argument('--tumor_model', type=str, required=True,
217
                help='Path to checkpoint folder for tumor segmentation.')
218
        self.parser.add_argument('--skull_model', type=str, default='',
219
                help='Path to checkpoint folder for skull-stripping segmentation.')
220
221
        # Input normalization parameters.
222
        self.parser.add_argument('--order', type=int, default=3,
223
                help='Order of interpolation function to be used in voxel resizing.')
224
        self.parser.add_argument('--mode', type=str, default='reflect',
225
                help='Method of handling image edges in interpolation.')
226
227
        # Test time augmentation and segmentation.
228
        self.parser.add_argument('--spatial_tta', action='store_true', default=True,
229
                help='Whether to apply spatial augmentation on all spatial axes.')
230
        self.parser.add_argument('--channel_tta', type=int, default=0,
231
                help='Additional intensity shifting samples to take.')
232
        self.parser.add_argument('--threshold', type=float, default=0.5,
233
                help='Threshold at which to create mask from probabilities.')
234
        self.parser.add_argument('--gpu', action='store_true', default=False,
235
                help='Whether to evaluate on GPU.')
236
237
    def parse_args(self):
238
        args = self.parser.parse_args()
239
        args.modalities = args.modalities.split(',')
240
        args.in_locs = args.in_locs.split(',')
241
242
        # Assert proper combination of inputs.
243
        assert args.threshold > 0 and args.threshold < 1, \
244
            'Threshold must be a probability between (0, 1).'
245
        if args.skull_model:
246
            assert args.skull_prepro, 'Need skull preprocessing stats if model is provided.'
247
        args.skull_strip = bool(args.skull_model)
248
249
        # Load model args.
250
        with open(os.path.join(args.tumor_model, 'train_args.pkl'), 'rb') as f:
251
            train_args = pickle.load(f)
252
            args.tumor_model_args = train_args['model_args']
253
            args.tumor_spatial_res = 2 ** args.tumor_model_args['depth']
254
            args.tumor_crop_size = train_args['crop_size']
255
        if args.skull_model:
256
            with open(os.path.join(args.skull_model, 'train_args.pkl'), 'rb') as f:
257
                train_args = pickle.load(f)
258
                args.skull_model_args = train_args['model_args']
259
                args.skull_spatial_res = 2 ** args.skull_model_args['depth']
260
                args.skull_crop_size = train_args['crop_size']
261
262
        # Load prepro stats.
263
        args.tumor_prepro = np.load(args.tumor_prepro).item()
264
        if args.skull_prepro:
265
            args.skull_prepro = np.load(args.skull_prepro).item()
266
267
        # Check data format and GPU compatibility.
268
        args.device = '/device:GPU:0' if args.gpu else '/cpu:0'
269
        if not args.gpu:
270
            assert args.tumor_model_args['data_format'] == 'channels_last' and args.skull_model_args['data_format'], \
271
                'tf.keras.layers.Conv3D only supports `channels_last` input for CPU.'
272
273
        return args