unknownBrain commited on
Commit
ee594f0
·
verified ·
1 Parent(s): 232c308

Upload all remaining preprocessing, standalone, test and utility files

Browse files
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ code/cooperative.pdf filter=lfs diff=lfs merge=lfs -text
code/CMTLNet.png ADDED

Git LFS Details

  • SHA256: a853b821eaecf417dc80cb6cc4bb20d040ea6ca37e3b8a851a76382d54908f26
  • Pointer size: 132 Bytes
  • Size of remote file: 1.82 MB
code/Train_CMTLNet_Step2_backup.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
3
+ import torch
4
+ import config
5
+ import monai
6
+ import warnings
7
+ import numpy as np
8
+ import pandas as pd
9
+ from model.CMTLNet import CMTLNet
10
+ from torch.nn import CrossEntropyLoss
11
+ from torch.utils.data import DataLoader
12
+ from torch.optim.lr_scheduler import ReduceLROnPlateau
13
+ from dataLoder.loader_S2 import TrainDataLoader_balance as TrainDataLoader
14
+ from dataLoder.loader_S2 import TestDataLoader
15
+ from utiles import save_model, get_learning_rate, calculate_classification_metrics, move_tensor_to_device, AverageMeter
16
+ from survivalstandalone.losses import cox_ph_loss
17
+
18
+ def validate(data_loader, model, mode_flag, ssl_index, class_name):
19
+ """
20
+ Validates the model on a given dataset and computes loss and classification metrics.
21
+
22
+ Parameters:
23
+ data_loader (DataLoader): DataLoader for the dataset to validate.
24
+ model (torch.nn.Module): The model to validate.
25
+ mode_flag (str): Indicates whether the dataset is 'Train' or 'Test'.
26
+ ssl_index (int): SSL index used for model prediction.
27
+ class_name (str): Name of the class/category being validated.
28
+
29
+ Returns:
30
+ tuple: Contains average loss, accuracy, F1 score, precision, and recall.
31
+ """
32
+ model.eval() # Set model to evaluation mode
33
+ cross_entropy_loss = CrossEntropyLoss(reduction='mean') # Define cross-entropy loss
34
+ all_targets, all_predictions = [], [] # Lists to store all true labels and predictions
35
+ loss_meter = AverageMeter() # Utility to track average loss
36
+
37
+ for batch_data in data_loader:
38
+ images, labels = batch_data
39
+ images = move_tensor_to_device(images, use_gpu=config.use_cuda) # Move images to GPU if available
40
+ labels = move_tensor_to_device(labels, use_gpu=config.use_cuda) # Move labels to GPU if available
41
+
42
+ with torch.no_grad(): # Disable gradient computation
43
+ outputs = model.predict(images, ssl_index) # Get model predictions
44
+ loss = cross_entropy_loss(outputs, labels) # Compute loss
45
+ loss_meter.update(loss.item(), 1) # Update loss meter
46
+ probabilities = torch.nn.functional.softmax(outputs, dim=1) # Compute probabilities
47
+ predicted_classes = torch.argmax(probabilities, dim=1).cpu().numpy() # Get predicted classes
48
+ true_labels = labels.cpu().detach().numpy() # Get true labels
49
+ all_predictions.extend(predicted_classes) # Collect predictions
50
+ all_targets.extend(true_labels) # Collect true labels
51
+
52
+ average_loss = loss_meter.average # Calculate average loss
53
+ all_predictions = np.array(all_predictions, dtype=np.int32)
54
+ all_targets = np.array(all_targets, dtype=np.int32)
55
+ # Compute classification metrics: Accuracy, F1, Precision, Recall, and Confusion Matrix
56
+ accuracy, f1, precision, recall, confusion_matrix = calculate_classification_metrics(
57
+ predictions=all_predictions,
58
+ targets=all_targets,
59
+ average_method="macro"
60
+ )
61
+ print(confusion_matrix) # Print confusion matrix
62
+
63
+ # Print metrics based on whether it's training or testing
64
+ if mode_flag == 'Test':
65
+ print(f'Test set {class_name} | Accuracy {accuracy:.4f} | F1 {f1:.4f} | Precision {precision:.4f} | Recall {recall:.4f} |')
66
+ else:
67
+ print(f'Train set {class_name} | Accuracy {accuracy:.4f} | F1 {f1:.4f} | Precision {precision:.4f} | Recall {recall:.4f} |')
68
+
69
+ model.train() # Set model back to training mode
70
+
71
+ return average_loss, accuracy, f1, precision, recall
72
+
73
+
74
+ def valid_metrics_by_class(model, train_loader, test_loader, ssl_index, class_name):
75
+ """
76
+ Computes validation metrics for a specific class on both training and testing datasets.
77
+
78
+ Parameters:
79
+ model (torch.nn.Module): The model to validate.
80
+ train_loader (DataLoader): DataLoader for the training dataset.
81
+ test_loader (DataLoader): DataLoader for the testing dataset.
82
+ ssl_index (int): SSL index used for model prediction.
83
+ class_name (str): Name of the class/category being validated.
84
+
85
+ Returns:
86
+ tuple: Contains training metrics and testing metrics.
87
+ """
88
+ # Validate on training data
89
+ train_loss, train_accuracy, train_f1, train_precision, train_recall = validate(
90
+ data_loader=train_loader,
91
+ model=model,
92
+ mode_flag='Train',
93
+ ssl_index=ssl_index,
94
+ class_name=class_name
95
+ )
96
+
97
+ # Validate on testing data
98
+ test_loss, test_accuracy, test_f1, test_precision, test_recall = validate(
99
+ data_loader=test_loader,
100
+ model=model,
101
+ mode_flag='Test',
102
+ ssl_index=ssl_index,
103
+ class_name=class_name
104
+ )
105
+
106
+ # Collect training and testing metrics
107
+ metrics_train = [train_loss, train_accuracy, train_f1, train_precision, train_recall]
108
+ metrics_test = [test_loss, test_accuracy, test_f1, test_precision, test_recall]
109
+ return metrics_train, metrics_test
110
+
111
+
112
+ def get_pandas_series(epoch, train_metrics, test_metrics):
113
+ """
114
+ Creates a Pandas Series for logging metrics.
115
+
116
+ Parameters:
117
+ epoch (int): Current epoch number.
118
+ train_metrics (list): List of training metrics.
119
+ test_metrics (list): List of testing metrics.
120
+
121
+ Returns:
122
+ pd.Series: Series containing epoch and corresponding metrics.
123
+ """
124
+ series = pd.Series([
125
+ epoch,
126
+ train_metrics[0], # Training loss
127
+ train_metrics[1], # Training accuracy
128
+ train_metrics[2], # Training F1 score
129
+ test_metrics[0], # Testing loss
130
+ test_metrics[1], # Testing accuracy
131
+ test_metrics[2], # Testing F1 score
132
+ ], index=[
133
+ 'epoch',
134
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
135
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
136
+ ])
137
+ return series
138
+
139
+
140
+ def get_class_loaders(TrainDataset, TestDataset, transforms, fold, loader_id, pkl_path):
141
+ """
142
+ Creates DataLoaders for training and validation datasets for a specific class.
143
+
144
+ Parameters:
145
+ TrainDataset (Dataset): Training dataset class.
146
+ TestDataset (Dataset): Testing dataset class.
147
+ transforms (Compose): Data transformation pipeline.
148
+ fold (int): Current fold number for cross-validation.
149
+ loader_id (str): Identifier for the class.
150
+ pkl_path (str): Path to the pickle file containing dataset information.
151
+
152
+ Returns:
153
+ tuple: Contains training DataLoader, validation training DataLoader, and validation testing DataLoader.
154
+ """
155
+ # Create training dataset
156
+ train_dataset = TrainDataset(
157
+ mode='train',
158
+ fold=fold,
159
+ transform=transforms,
160
+ pickle_path=pkl_path
161
+ )
162
+
163
+ # Create training DataLoader
164
+ train_loader = DataLoader(
165
+ train_dataset,
166
+ batch_size=config.batch_size,
167
+ shuffle=True,
168
+ drop_last=True,
169
+ num_workers=config.n_threads,
170
+ pin_memory=config.use_cuda
171
+ )
172
+ print(f"Number of train_loader {loader_id} examples {len(train_dataset)}")
173
+
174
+ # Create validation training dataset
175
+ val_train_dataset = TestDataset(
176
+ mode='train',
177
+ fold=fold,
178
+ transform=transforms,
179
+ pickle_path=pkl_path
180
+ )
181
+
182
+ # Create validation training DataLoader
183
+ val_train_loader = DataLoader(
184
+ val_train_dataset,
185
+ batch_size=1,
186
+ shuffle=False,
187
+ drop_last=False,
188
+ num_workers=config.n_threads,
189
+ pin_memory=config.use_cuda
190
+ )
191
+ print(f"Number of val_train_loader {loader_id} examples {len(val_train_dataset)}")
192
+
193
+ # Create validation testing dataset
194
+ val_test_dataset = TestDataset(
195
+ mode='test',
196
+ fold=fold,
197
+ transform=transforms,
198
+ pickle_path=pkl_path
199
+ )
200
+
201
+ # Create validation testing DataLoader
202
+ val_loader = DataLoader(
203
+ val_test_dataset,
204
+ batch_size=1,
205
+ shuffle=False,
206
+ drop_last=False,
207
+ num_workers=config.n_threads,
208
+ pin_memory=config.use_cuda
209
+ )
210
+ print(f"Number of val_loader {loader_id} examples {len(val_test_dataset)}")
211
+ return train_loader, val_train_loader, val_loader
212
+
213
+ def reshape_input_data(data):
214
+ images, labels, times, events = data
215
+ images = images.view(images.size(0) * images.size(1), images.size(2), images.size(3), images.size(4), images.size(5))
216
+ labels = labels.view(-1)
217
+ times = times.view(-1)
218
+ events = events.view(-1)
219
+
220
+ images = move_tensor_to_device(images, use_gpu=config.use_cuda)
221
+ labels = move_tensor_to_device(labels, use_gpu=config.use_cuda)
222
+ times = move_tensor_to_device(times, use_gpu=config.use_cuda)
223
+ events = move_tensor_to_device(events, use_gpu=config.use_cuda)
224
+ return images, labels, times, events
225
+
226
+
227
+ def train(fold, pkl_paths):
228
+ """
229
+ Main training function responsible for the entire training process, including data loading, model training,
230
+ validation, logging, and model saving.
231
+
232
+ Parameters:
233
+ fold (int): Current fold number for cross-validation.
234
+ pkl_paths (list): List of paths to pickle files for each class.
235
+ """
236
+ # Define data transformations
237
+ val_transforms = monai.transforms.Compose([
238
+ monai.transforms.ToTensor(),
239
+ ])
240
+
241
+ # Get DataLoaders for each class
242
+ train_loader_1p19q, val_train_loader_1p19q, val_loader_1p19q = get_class_loaders(
243
+ TrainDataset=TrainDataLoader,
244
+ TestDataset=TestDataLoader,
245
+ transforms=val_transforms,
246
+ fold=fold,
247
+ loader_id='1p19q',
248
+ pkl_path=pkl_paths[0]
249
+ )
250
+ train_loader_IDH, val_train_loader_IDH, val_loader_IDH = get_class_loaders(
251
+ TrainDataset=TrainDataLoader,
252
+ TestDataset=TestDataLoader,
253
+ transforms=val_transforms,
254
+ fold=fold,
255
+ loader_id='IDH',
256
+ pkl_path=pkl_paths[1]
257
+ )
258
+ train_loader_LHG, val_train_loader_LHG, val_loader_LHG = get_class_loaders(
259
+ TrainDataset=TrainDataLoader,
260
+ TestDataset=TestDataLoader,
261
+ transforms=val_transforms,
262
+ fold=fold,
263
+ loader_id='LHG',
264
+ pkl_path=pkl_paths[2]
265
+ )
266
+
267
+ # Move model to GPU if available
268
+ if config.use_cuda:
269
+ model.cuda()
270
+
271
+ cross_entropy_loss = CrossEntropyLoss(reduction='mean') # Define cross-entropy loss
272
+
273
+ # Only optimize parameters that require gradients
274
+ optim_parameters = filter(lambda p: p.requires_grad, model.parameters())
275
+ optimizer = torch.optim.Adam(
276
+ optim_parameters,
277
+ lr=config.lr_self,
278
+ weight_decay=config.weight_decay
279
+ ) # Using Adam optimizer
280
+
281
+ # Learning rate scheduler
282
+ scheduler = ReduceLROnPlateau(
283
+ optimizer=optimizer,
284
+ factor=config.lr_reduce_factor,
285
+ patience=config.lr_reduce_patience,
286
+ mode='max',
287
+ min_lr=config.min_lr
288
+ )
289
+
290
+ global_step = 0 # Initialize global step
291
+ best_score = -1 # Initialize best score
292
+
293
+ # Initialize DataFrames for logging
294
+ log_1p19q = pd.DataFrame(columns=[
295
+ 'epoch',
296
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
297
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
298
+ ])
299
+
300
+ log_IDH = pd.DataFrame(columns=[
301
+ 'epoch',
302
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
303
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
304
+ ])
305
+
306
+ log_LHG = pd.DataFrame(columns=[
307
+ 'epoch',
308
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
309
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
310
+ ])
311
+
312
+ log_mean = pd.DataFrame(columns=[
313
+ 'epoch',
314
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
315
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
316
+ ])
317
+
318
+ model.train() # Set model to training mode
319
+
320
+ # Initialize iterator indices
321
+ iter_index_IDH = 0
322
+ iter_index_LHG = 0
323
+
324
+ iter_IDH = iter(train_loader_IDH)
325
+ iter_LHG = iter(train_loader_LHG)
326
+
327
+ for epoch in range(config.epochs_s2):
328
+ if epoch == config.save_epoch:
329
+ best_score = -1 # Reset best score at a specific epoch
330
+
331
+ iter_1p19q = iter(train_loader_1p19q) # Get iterator for 1p19q class
332
+ for batch_idx in range(len(train_loader_1p19q)):
333
+ iter_index_IDH += 1
334
+ iter_index_LHG += 1
335
+
336
+ # Reset iterators if they exceed dataset length
337
+ if iter_index_IDH >= len(train_loader_IDH):
338
+ iter_IDH = iter(train_loader_IDH)
339
+ iter_index_IDH = 0
340
+
341
+ if iter_index_LHG >= len(train_loader_LHG):
342
+ iter_LHG = iter(train_loader_LHG)
343
+ iter_index_LHG = 0
344
+
345
+ # Get data for each class
346
+ data_1p19q = next(iter_1p19q)
347
+ data_IDH = next(iter_IDH)
348
+ data_LHG = next(iter_LHG)
349
+
350
+ # Reshape input data
351
+ # Reshape input data
352
+ imgs_1p19q, label_1p19q, time_1p19q, event_1p19q = reshape_input_data(data_1p19q)
353
+ imgs_IDH, label_IDH, time_IDH, event_IDH = reshape_input_data(data_IDH)
354
+ imgs_LHG, label_LHG, time_LHG, event_LHG = reshape_input_data(data_LHG)
355
+
356
+ # Combine inputs and targets
357
+ label_list = [label_1p19q, label_IDH, label_LHG]
358
+ combined_input = torch.cat((imgs_1p19q, imgs_IDH, imgs_LHG), dim=0)
359
+ combined_times = torch.cat((time_1p19q, time_IDH, time_LHG), dim=0)
360
+ combined_events = torch.cat((event_1p19q, event_IDH, event_LHG), dim=0)
361
+
362
+ condition_1p19q = torch.tensor(0, dtype=torch.long, device=label_1p19q.device).repeat(1, label_1p19q.size(0))[0]
363
+ condition_IDH = torch.tensor(1, dtype=torch.long, device=label_IDH.device).repeat(1, label_IDH.size(0))[0]
364
+ condition_LHG = torch.tensor(2, dtype=torch.long, device=label_LHG.device).repeat(1, label_LHG.size(0))[0]
365
+ condition = torch.cat([condition_1p19q, condition_IDH, condition_LHG], dim=0)
366
+
367
+ # Forward pass (now receives risk_scores)
368
+ (out_cls_list_UFE, out_cls_labels_UFE,
369
+ out_cls_list_UCFC, out_cls_labels_UCFC, risk_scores) = model(combined_input, label_list, condition)
370
+
371
+ # --- CALCULATE COX LOSS ---
372
+ # Mask out patients who don't have survival data (time == 0)
373
+ valid_mask = combined_times > 0
374
+ if valid_mask.sum() >= 2: # Cox loss needs at least a pair to rank
375
+ loss_surv = cox_ph_loss(risk_scores[valid_mask], combined_times[valid_mask], combined_events[valid_mask])
376
+ else:
377
+ loss_surv = torch.tensor(0.0, device=risk_scores.device, requires_grad=True)
378
+
379
+ # Classification losses
380
+ loss_cls_U1 = cross_entropy_loss(out_cls_list_UFE[0], out_cls_labels_UFE[0])
381
+ loss_cls_U2 = cross_entropy_loss(out_cls_list_UFE[1], out_cls_labels_UFE[1])
382
+ loss_cls_U3 = cross_entropy_loss(out_cls_list_UFE[2], out_cls_labels_UFE[2])
383
+ loss_cls_1 = cross_entropy_loss(out_cls_list_UCFC[0], out_cls_labels_UCFC[0])
384
+ loss_cls_2 = cross_entropy_loss(out_cls_list_UCFC[1], out_cls_labels_UCFC[1])
385
+ loss_cls_3 = cross_entropy_loss(out_cls_list_UCFC[2], out_cls_labels_UCFC[2])
386
+
387
+ # Total loss (weighing survival by 0.5 so it doesn't overpower classification)
388
+ total_loss = loss_cls_U1 + loss_cls_U2 + loss_cls_U3 + loss_cls_1 + loss_cls_2 + loss_cls_3 + (0.5 * loss_surv)
389
+
390
+ # Backward pass
391
+ optimizer.zero_grad()
392
+ total_loss.backward()
393
+ optimizer.step()
394
+
395
+ # Get current learning rate
396
+ current_lr = get_learning_rate(optimizer)
397
+ print(f'Global_Step {global_step} | Train Epoch: {epoch} | lr {current_lr:.2e} |')
398
+
399
+ # Define save path
400
+ save_path = os.path.join(config.data_dir, 'results', str(save_name), f'Fold_{fold}')
401
+ if not os.path.exists(save_path):
402
+ os.makedirs(save_path)
403
+
404
+ # Compute metrics for each class
405
+ metrics_train_1p19q, metrics_test_1p19q = valid_metrics_by_class(
406
+ model=model,
407
+ train_loader=val_train_loader_1p19q,
408
+ test_loader=val_loader_1p19q,
409
+ ssl_index=0,
410
+ class_name='1p19q'
411
+ )
412
+
413
+ metrics_train_IDH, metrics_test_IDH = valid_metrics_by_class(
414
+ model=model,
415
+ train_loader=val_train_loader_IDH,
416
+ test_loader=val_loader_IDH,
417
+ ssl_index=1,
418
+ class_name='IDH'
419
+ )
420
+
421
+ metrics_train_LHG, metrics_test_LHG = valid_metrics_by_class(
422
+ model=model,
423
+ train_loader=val_train_loader_LHG,
424
+ test_loader=val_loader_LHG,
425
+ ssl_index=2,
426
+ class_name='LHG'
427
+ )
428
+
429
+ # Calculate mean metrics across classes
430
+ metrics_train_mean = (np.array(metrics_train_1p19q) + np.array(metrics_train_IDH) +
431
+ np.array(metrics_train_LHG)) / 3.0
432
+ metrics_test_mean = (np.array(metrics_test_1p19q) + np.array(metrics_test_IDH) +
433
+ np.array(metrics_test_LHG)) / 3.0
434
+
435
+ # Create log entries
436
+ log_entry_1p19q = get_pandas_series(epoch, metrics_train_1p19q, metrics_test_1p19q)
437
+ log_entry_IDH = get_pandas_series(epoch, metrics_train_IDH, metrics_test_IDH)
438
+ log_entry_LHG = get_pandas_series(epoch, metrics_train_LHG, metrics_test_LHG)
439
+ log_entry_mean = get_pandas_series(epoch, metrics_train_mean, metrics_test_mean)
440
+
441
+ # Append logs to DataFrames and save to CSV
442
+ log_1p19q = log_1p19q.append(log_entry_1p19q, ignore_index=True)
443
+ log_1p19q.to_csv(os.path.join(save_path, 'log_1p19q.csv'), index=False)
444
+
445
+ log_IDH = log_IDH.append(log_entry_IDH, ignore_index=True)
446
+ log_IDH.to_csv(os.path.join(save_path, 'log_IDH.csv'), index=False)
447
+
448
+ log_LHG = log_LHG.append(log_entry_LHG, ignore_index=True)
449
+ log_LHG.to_csv(os.path.join(save_path, 'log_LHG.csv'), index=False)
450
+
451
+ log_mean = log_mean.append(log_entry_mean, ignore_index=True)
452
+ log_mean.to_csv(os.path.join(save_path, 'log_mean.csv'), index=False)
453
+
454
+ # Use the mean F1 score from the test set as the evaluation metric
455
+ current_f1 = metrics_test_mean[2]
456
+
457
+ # Save the best model based on F1 score
458
+ if epoch >= config.save_epoch:
459
+ if current_f1 > best_score:
460
+ save_config = {
461
+ 'name': save_name,
462
+ 'save_dir': save_path,
463
+ 'global_step': global_step,
464
+ 'Test_F1': current_f1
465
+ }
466
+ save_model(model=model, config=save_config)
467
+ best_score = current_f1
468
+
469
+ # Update the best score if current F1 is better
470
+ if current_f1 > best_score:
471
+ best_score = current_f1
472
+
473
+ # Step the scheduler based on the best score
474
+ scheduler.step(best_score)
475
+
476
+
477
+ if __name__ == '__main__':
478
+ # Ignore all warnings
479
+ warnings.filterwarnings("ignore")
480
+
481
+ # Set random seeds for reproducibility
482
+ seed = config.random_seed
483
+ np.random.seed(seed) # Python's random seed
484
+ os.environ['PYTHONHASHSEED'] = str(seed) # Disable Python hash randomization
485
+ torch.manual_seed(seed) # Torch CPU random seed
486
+ torch.cuda.manual_seed(seed) # Torch GPU random seed
487
+ torch.cuda.manual_seed_all(seed) # Torch multi-GPU random seed
488
+ torch.backends.cudnn.benchmark = False # Disable cuDNN benchmark
489
+ torch.backends.cudnn.deterministic = True # Enable deterministic algorithms
490
+
491
+ # Define paths to pickle files for each class
492
+ pkl_paths = [
493
+ './1p19q.pkl',
494
+ './IDH.pkl',
495
+ './LHG.pkl'
496
+ ]
497
+
498
+ Base_CEF_model_paths = [
499
+ './Fold_0/CFE.pkl',
500
+ './Fold_1/CFE.pkl',
501
+ './Fold_2/CFE.pkl',
502
+ './Fold_3/CFE.pkl',
503
+ './Fold_4/CFE.pkl'
504
+ ]
505
+
506
+ # Perform 5-fold cross-validation training
507
+ for fold in range(5):
508
+ model = CMTLNet(in_channels=3, num_classes=2, Arcm=0.5, multi=3) # Initialize the model
509
+ model_basic_CFE = torch.load(Base_CEF_model_paths[fold], weights_only=False)
510
+ model.ShareTask.load_state_dict(model_basic_CFE.state_dict())
511
+ save_name = model.name # Get the model's name
512
+ print(f"{save_name}_Fold_{fold}")
513
+ train(fold, pkl_paths) # Start training
code/checkdata.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+ # Path to your metadata file
4
+ file_path = "clinicaldata.csv"
5
+
6
+ # Load the data as a CSV
7
+ # If it throws a Unicode error, sometimes adding encoding='latin1' or encoding='utf-8-sig' helps
8
+ try:
9
+ df = pd.read_csv(file_path)
10
+ except UnicodeDecodeError:
11
+ df = pd.read_csv(file_path, encoding='latin1')
12
+
13
+ # Print the column names
14
+ print("Available columns in the dataset:")
15
+ print(df.columns.tolist())
16
+
17
+ # Show the first 5 rows
18
+ print("\nFirst 5 rows:")
19
+ print(df.head())
code/cooperative.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:909b5f30c9fd83ff0ea12b9db3dd18c7d8361920f214cd9040a31d284fe48e96
3
+ size 3914753
code/diff.patch ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --- Train_CMTLNet_Step2_backup.py 2026-09-22 12:39:24.191187225 +0530
2
+ +++ Train_CMTLNet_Step2.py 2026-09-22 12:41:51.246139213 +0530
3
+ @@ -1,4 +1,9 @@
4
+ import os
5
+ +import glob
6
+ +import gc
7
+ +import wandb
8
+ +from torch.cuda.amp import autocast, GradScaler
9
+ +from huggingface_hub import upload_file
10
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
11
+ import torch
12
+ import config
13
+ @@ -289,6 +294,33 @@
14
+
15
+ global_step = 0 # Initialize global step
16
+ best_score = -1 # Initialize best score
17
+ + start_epoch = 0
18
+ + scaler = GradScaler()
19
+ + save_name = getattr(model, 'name', 'UFE_UCFC')
20
+ + save_path = os.path.join(config.data_dir, 'results', 'UFE_UCFC', f'Fold_{fold}')
21
+ + if not os.path.exists(save_path):
22
+ + os.makedirs(save_path)
23
+ +
24
+ + # Resume logic
25
+ + import glob
26
+ + checkpoints = glob.glob(os.path.join(save_path, f'checkpoint_fold{fold}_epoch*.pkl'))
27
+ + if checkpoints:
28
+ + latest_checkpoint = max(checkpoints, key=lambda x: int(x.split('epoch')[1].split('.pkl')[0]))
29
+ + print(f"Resuming from checkpoint: {latest_checkpoint}")
30
+ + checkpoint = torch.load(latest_checkpoint, weights_only=False)
31
+ + model.load_state_dict(checkpoint['model_state_dict'])
32
+ + if 'optimizer_state_dict' in checkpoint:
33
+ + optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
34
+ + if 'scheduler_state_dict' in checkpoint:
35
+ + scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
36
+ + if 'scaler_state_dict' in checkpoint:
37
+ + scaler.load_state_dict(checkpoint['scaler_state_dict'])
38
+ + if 'global_step' in checkpoint:
39
+ + global_step = checkpoint['global_step']
40
+ + if 'best_f1' in checkpoint:
41
+ + best_score = checkpoint['best_f1']
42
+ + if 'epoch' in checkpoint:
43
+ + start_epoch = checkpoint['epoch'] + 1
44
+
45
+ # Initialize DataFrames for logging
46
+ log_1p19q = pd.DataFrame(columns=[
47
+ @@ -324,7 +356,7 @@
48
+ iter_IDH = iter(train_loader_IDH)
49
+ iter_LHG = iter(train_loader_LHG)
50
+
51
+ - for epoch in range(config.epochs_s2):
52
+ + for epoch in range(start_epoch, config.epochs_s2):
53
+ if epoch == config.save_epoch:
54
+ best_score = -1 # Reset best score at a specific epoch
55
+
56
+ @@ -364,42 +396,38 @@
57
+ condition_LHG = torch.tensor(2, dtype=torch.long, device=label_LHG.device).repeat(1, label_LHG.size(0))[0]
58
+ condition = torch.cat([condition_1p19q, condition_IDH, condition_LHG], dim=0)
59
+
60
+ - # Forward pass (now receives risk_scores)
61
+ - (out_cls_list_UFE, out_cls_labels_UFE,
62
+ - out_cls_list_UCFC, out_cls_labels_UCFC, risk_scores) = model(combined_input, label_list, condition)
63
+ -
64
+ - # --- CALCULATE COX LOSS ---
65
+ - # Mask out patients who don't have survival data (time == 0)
66
+ - valid_mask = combined_times > 0
67
+ - if valid_mask.sum() >= 2: # Cox loss needs at least a pair to rank
68
+ - loss_surv = cox_ph_loss(risk_scores[valid_mask], combined_times[valid_mask], combined_events[valid_mask])
69
+ - else:
70
+ - loss_surv = torch.tensor(0.0, device=risk_scores.device, requires_grad=True)
71
+ -
72
+ - # Classification losses
73
+ - loss_cls_U1 = cross_entropy_loss(out_cls_list_UFE[0], out_cls_labels_UFE[0])
74
+ - loss_cls_U2 = cross_entropy_loss(out_cls_list_UFE[1], out_cls_labels_UFE[1])
75
+ - loss_cls_U3 = cross_entropy_loss(out_cls_list_UFE[2], out_cls_labels_UFE[2])
76
+ - loss_cls_1 = cross_entropy_loss(out_cls_list_UCFC[0], out_cls_labels_UCFC[0])
77
+ - loss_cls_2 = cross_entropy_loss(out_cls_list_UCFC[1], out_cls_labels_UCFC[1])
78
+ - loss_cls_3 = cross_entropy_loss(out_cls_list_UCFC[2], out_cls_labels_UCFC[2])
79
+ + # Forward pass with AMP
80
+ + with autocast():
81
+ + (out_cls_list_UFE, out_cls_labels_UFE,
82
+ + out_cls_list_UCFC, out_cls_labels_UCFC, risk_scores) = model(combined_input, label_list, condition)
83
+ +
84
+ + # --- CALCULATE COX LOSS ---
85
+ + valid_mask = combined_times > 0
86
+ + if valid_mask.sum() >= 2:
87
+ + loss_surv = cox_ph_loss(risk_scores[valid_mask], combined_times[valid_mask], combined_events[valid_mask])
88
+ + else:
89
+ + loss_surv = torch.tensor(0.0, device=risk_scores.device, requires_grad=True)
90
+ +
91
+ + loss_cls_U1 = cross_entropy_loss(out_cls_list_UFE[0], out_cls_labels_UFE[0])
92
+ + loss_cls_U2 = cross_entropy_loss(out_cls_list_UFE[1], out_cls_labels_UFE[1])
93
+ + loss_cls_U3 = cross_entropy_loss(out_cls_list_UFE[2], out_cls_labels_UFE[2])
94
+ + loss_cls_1 = cross_entropy_loss(out_cls_list_UCFC[0], out_cls_labels_UCFC[0])
95
+ + loss_cls_2 = cross_entropy_loss(out_cls_list_UCFC[1], out_cls_labels_UCFC[1])
96
+ + loss_cls_3 = cross_entropy_loss(out_cls_list_UCFC[2], out_cls_labels_UCFC[2])
97
+
98
+ - # Total loss (weighing survival by 0.5 so it doesn't overpower classification)
99
+ - total_loss = loss_cls_U1 + loss_cls_U2 + loss_cls_U3 + loss_cls_1 + loss_cls_2 + loss_cls_3 + (0.5 * loss_surv)
100
+ + total_loss = loss_cls_U1 + loss_cls_U2 + loss_cls_U3 + loss_cls_1 + loss_cls_2 + loss_cls_3 + (0.5 * loss_surv)
101
+
102
+ - # Backward pass
103
+ + # Backward pass with AMP
104
+ optimizer.zero_grad()
105
+ - total_loss.backward()
106
+ - optimizer.step()
107
+ + scaler.scale(total_loss).backward()
108
+ + scaler.step(optimizer)
109
+ + scaler.update()
110
+
111
+ # Get current learning rate
112
+ current_lr = get_learning_rate(optimizer)
113
+ print(f'Global_Step {global_step} | Train Epoch: {epoch} | lr {current_lr:.2e} |')
114
+
115
+ - # Define save path
116
+ - save_path = os.path.join(config.data_dir, 'results', str(save_name), f'Fold_{fold}')
117
+ - if not os.path.exists(save_path):
118
+ - os.makedirs(save_path)
119
+ +
120
+
121
+ # Compute metrics for each class
122
+ metrics_train_1p19q, metrics_test_1p19q = valid_metrics_by_class(
123
+ @@ -439,16 +467,16 @@
124
+ log_entry_mean = get_pandas_series(epoch, metrics_train_mean, metrics_test_mean)
125
+
126
+ # Append logs to DataFrames and save to CSV
127
+ - log_1p19q = log_1p19q.append(log_entry_1p19q, ignore_index=True)
128
+ + log_1p19q = pd.concat([log_1p19q, log_entry_1p19q.to_frame().T], ignore_index=True)
129
+ log_1p19q.to_csv(os.path.join(save_path, 'log_1p19q.csv'), index=False)
130
+
131
+ - log_IDH = log_IDH.append(log_entry_IDH, ignore_index=True)
132
+ + log_IDH = pd.concat([log_IDH, log_entry_IDH.to_frame().T], ignore_index=True)
133
+ log_IDH.to_csv(os.path.join(save_path, 'log_IDH.csv'), index=False)
134
+
135
+ - log_LHG = log_LHG.append(log_entry_LHG, ignore_index=True)
136
+ + log_LHG = pd.concat([log_LHG, log_entry_LHG.to_frame().T], ignore_index=True)
137
+ log_LHG.to_csv(os.path.join(save_path, 'log_LHG.csv'), index=False)
138
+
139
+ - log_mean = log_mean.append(log_entry_mean, ignore_index=True)
140
+ + log_mean = pd.concat([log_mean, log_entry_mean.to_frame().T], ignore_index=True)
141
+ log_mean.to_csv(os.path.join(save_path, 'log_mean.csv'), index=False)
142
+
143
+ # Use the mean F1 score from the test set as the evaluation metric
144
+ @@ -464,6 +492,37 @@
145
+ 'Test_F1': current_f1
146
+ }
147
+ save_model(model=model, config=save_config)
148
+ +
149
+ + # Reconstruct path generated by save_model to upload it
150
+ + f1_percentage = current_f1 * 100
151
+ + best_path = os.path.join(save_path, f"{save_name}_F1_{f1_percentage:.2f}_step_{global_step}.pkl")
152
+ +
153
+ + best_model_name = f'best_model_fold{fold}.pkl'
154
+ + best_model_path = os.path.join(save_path, best_model_name)
155
+ + import shutil
156
+ + if os.path.exists(best_path):
157
+ + shutil.copy(best_path, best_model_path)
158
+ +
159
+ + # Upload best model to W&B
160
+ + if wandb.run is not None:
161
+ + wandb.save(best_model_path)
162
+ +
163
+ + # Upload best model to Hugging Face
164
+ + hf_token = os.environ.get("HF_TOKEN")
165
+ + if hf_token and os.path.exists(best_model_path):
166
+ + try:
167
+ + from huggingface_hub import upload_file
168
+ + upload_file(
169
+ + path_or_fileobj=best_model_path,
170
+ + path_in_repo=f"best_models/Fold_{fold}/{best_model_name}",
171
+ + repo_id="jainamdedhia/cmtlnet-training",
172
+ + repo_type="dataset",
173
+ + token=hf_token,
174
+ + )
175
+ + print(f"☁️ Best model uploaded to Hugging Face: {best_model_name}")
176
+ + except Exception as e:
177
+ + print(f"⚠️ Hugging Face best model upload failed: {e}")
178
+ +
179
+ best_score = current_f1
180
+
181
+ # Update the best score if current F1 is better
182
+ @@ -472,6 +531,64 @@
183
+
184
+ # Step the scheduler based on the best score
185
+ scheduler.step(best_score)
186
+ +
187
+ + # ===== LIGHT CHECKPOINT EVERY 5 EPOCHS =====
188
+ + if epoch % 5 == 0 and epoch > 0:
189
+ + light_checkpoint_path = os.path.join(save_path, f'checkpoint_fold{fold}_epoch{epoch}.pkl')
190
+ + torch.save({
191
+ + 'epoch': epoch,
192
+ + 'fold': fold,
193
+ + 'model_state_dict': model.state_dict(),
194
+ + 'optimizer_state_dict': optimizer.state_dict(),
195
+ + 'scheduler_state_dict': scheduler.state_dict(),
196
+ + 'scaler_state_dict': scaler.state_dict(),
197
+ + 'best_f1': best_score,
198
+ + 'global_step': global_step
199
+ + }, light_checkpoint_path)
200
+ + print(f"✅ Light checkpoint saved locally: {light_checkpoint_path}")
201
+ +
202
+ + # Upload to W&B
203
+ + if wandb.run is not None:
204
+ + wandb.save(light_checkpoint_path)
205
+ + print(f"☁️ Uploaded to W&B: {light_checkpoint_path}")
206
+ +
207
+ + # Upload to Hugging Face
208
+ + hf_token = os.environ.get("HF_TOKEN")
209
+ + if hf_token:
210
+ + try:
211
+ + from huggingface_hub import upload_file
212
+ + filename_only = os.path.basename(light_checkpoint_path)
213
+ + upload_file(
214
+ + path_or_fileobj=light_checkpoint_path,
215
+ + path_in_repo=f"checkpoints/{filename_only}",
216
+ + repo_id="jainamdedhia/cmtlnet-training",
217
+ + repo_type="dataset",
218
+ + token=hf_token,
219
+ + )
220
+ + print(f"☁️ Uploaded to Hugging Face: {light_checkpoint_path}")
221
+ + except Exception as e:
222
+ + print(f"⚠️ Hugging Face upload failed: {e}")
223
+ + else:
224
+ + print("ℹ️ HF_TOKEN not set. Skipping Hugging Face upload.")
225
+ + # ===== END LIGHT CHECKPOINT =====
226
+ +
227
+ + # Log to W&B
228
+ + if wandb.run is not None:
229
+ + wandb.log({
230
+ + "Train/Mean_Loss": metrics_train_mean[0],
231
+ + "Train/Mean_Accuracy": metrics_train_mean[1],
232
+ + "Train/Mean_F1": metrics_train_mean[2],
233
+ + "Test/Mean_Loss": metrics_test_mean[0],
234
+ + "Test/Mean_Accuracy": metrics_test_mean[1],
235
+ + "Test/Mean_F1": metrics_test_mean[2],
236
+ + "Epoch": epoch,
237
+ + "Learning_Rate": current_lr,
238
+ + "Global_Step": global_step
239
+ + })
240
+ +
241
+ + # Safely empty cache at the end of the epoch
242
+ + gc.collect()
243
+ + torch.cuda.empty_cache()
244
+
245
+
246
+ if __name__ == '__main__':
247
+ @@ -495,19 +612,40 @@
248
+ './LHG.pkl'
249
+ ]
250
+
251
+ - Base_CEF_model_paths = [
252
+ - './Fold_0/CFE.pkl',
253
+ - './Fold_1/CFE.pkl',
254
+ - './Fold_2/CFE.pkl',
255
+ - './Fold_3/CFE.pkl',
256
+ - './Fold_4/CFE.pkl'
257
+ - ]
258
+ +
259
+
260
+ # Perform 5-fold cross-validation training
261
+ for fold in range(5):
262
+ + import glob
263
+ + import wandb
264
+ + cfe_pattern = f'results/CFE/Fold_{fold}/CFE_F1_*.pkl'
265
+ + cfe_files = glob.glob(cfe_pattern)
266
+ + if cfe_files:
267
+ + latest_cfe = max(cfe_files, key=os.path.getmtime)
268
+ + print(f"✅ Loading CFE model for Fold {fold}: {latest_cfe}")
269
+ + else:
270
+ + raise FileNotFoundError(f"No CFE checkpoint found for Fold {fold} in {cfe_pattern}")
271
+ +
272
+ model = CMTLNet(in_channels=3, num_classes=2, Arcm=0.5, multi=3) # Initialize the model
273
+ - model_basic_CFE = torch.load(Base_CEF_model_paths[fold], weights_only=False)
274
+ - model.ShareTask.load_state_dict(model_basic_CFE.state_dict())
275
+ - save_name = model.name # Get the model's name
276
+ + model = model.to(config.device if hasattr(config, 'device') else 'cuda')
277
+ + model_basic_CFE = torch.load(latest_cfe, weights_only=False)
278
+ + model.ShareTask.load_state_dict(model_basic_CFE.get('model_state_dict', model_basic_CFE.state_dict()) if isinstance(model_basic_CFE, dict) else model_basic_CFE.state_dict())
279
+ +
280
+ + save_name = getattr(model, 'name', 'UFE_UCFC')
281
+ print(f"{save_name}_Fold_{fold}")
282
+ - train(fold, pkl_paths) # Start training
283
+
284
+ +
285
+ + # Initialize wandb
286
+ + wandb.init(
287
+ + project="CMTLNet-Training",
288
+ + name=f"Step2-Fold-{fold}",
289
+ + config={
290
+ + 'epochs': config.epochs_s2,
291
+ + 'batch_size': config.batch_size,
292
+ + 'learning_rate': config.lr_self,
293
+ + 'num_workers': config.n_threads,
294
+ + },
295
+ + reinit=True
296
+ + )
297
+ +
298
+ + train(fold, pkl_paths) # Start training
299
+ + wandb.finish()
300
+
code/fix_dict_bug.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ with open('Train_CMTLNet_Step2_proposed.py', 'r') as f:
4
+ code = f.read()
5
+
6
+ old_line = "model.ShareTask.load_state_dict(model_basic_CFE.get('model_state_dict', model_basic_CFE.state_dict()) if isinstance(model_basic_CFE, dict) else model_basic_CFE.state_dict())"
7
+
8
+ new_lines = """if isinstance(model_basic_CFE, dict):
9
+ state_dict = model_basic_CFE.get('model_state_dict', model_basic_CFE)
10
+ else:
11
+ state_dict = model_basic_CFE.state_dict()
12
+ model.ShareTask.load_state_dict(state_dict)"""
13
+
14
+ if old_line in code:
15
+ code = code.replace(old_line, new_lines)
16
+ else:
17
+ print("Old line not found.")
18
+
19
+ with open('Train_CMTLNet_Step2_proposed.py', 'w') as f:
20
+ f.write(code)
21
+
code/fix_global_step.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ with open('Train_CMTLNet_Step2.py', 'r') as f:
4
+ code = f.read()
5
+
6
+ target = """ scaler.step(optimizer)
7
+ scaler.update()
8
+
9
+ # Get current learning rate"""
10
+
11
+ replacement = """ scaler.step(optimizer)
12
+ scaler.update()
13
+
14
+ global_step += 1
15
+
16
+ # Get current learning rate"""
17
+
18
+ if target in code:
19
+ code = code.replace(target, replacement)
20
+ with open('Train_CMTLNet_Step2.py', 'w') as f:
21
+ f.write(code)
22
+ print("Fixed global_step")
23
+ else:
24
+ print("Target not found")
code/fix_step1.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ with open('Train_CMTLNet_Step1.py', 'r') as f:
4
+ content = f.read()
5
+
6
+ # Remove tqdm import
7
+ content = re.sub(r'from tqdm import tqdm.*?\n', '', content)
8
+
9
+ # Remove Checkpoint prints
10
+ content = re.sub(r' *print\("\[Checkpoint \d/6\].*?\n', '', content)
11
+
12
+ # Replace tqdm loop with regular loop and add print statement
13
+ content = content.replace(
14
+ 'pbar = tqdm(range(len(train_loader_1p19q)), desc=f"Epoch {epoch}/{config.epochs_s1}", dynamic_ncols=True)\n \n for batch_idx in pbar:',
15
+ 'for batch_idx in range(len(train_loader_1p19q)):'
16
+ )
17
+
18
+ content = content.replace('pbar.set_postfix({"RAM": f"{mem_gb:.2f} GB"})', '')
19
+
20
+ # Insert the batch print
21
+ target = 'scaler.update()\n # --------------------------------------------------'
22
+ replacement = '''scaler.update()
23
+ # --------------------------------------------------
24
+
25
+ if batch_idx % 10 == 0:
26
+ print(f" [Epoch {epoch}] Batch {batch_idx}/{len(train_loader_1p19q)} | Loss: {total_loss.item():.4f} | RAM: {mem_gb:.2f} GB")'''
27
+
28
+ content = content.replace(target, replacement)
29
+
30
+ with open('Train_CMTLNet_Step1.py', 'w') as f:
31
+ f.write(content)
code/fix_step2.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+
4
+ with open('Train_CMTLNet_Step2.py', 'r') as f:
5
+ code = f.read()
6
+
7
+ # Fix 10: Imports
8
+ if 'import wandb' not in code:
9
+ code = code.replace('import os\n', 'import os\nimport glob\nimport gc\nimport wandb\nfrom torch.cuda.amp import autocast, GradScaler\nfrom huggingface_hub import upload_file\n')
10
+
11
+ # Fix 5: torch.load with weights_only=False
12
+ code = code.replace('torch.load(resume_path)', 'torch.load(resume_path, weights_only=False)')
13
+ code = code.replace('torch.load(Base_CEF_model_paths[fold])', 'torch.load(Base_CEF_model_paths[fold], weights_only=False)')
14
+ code = code.replace('torch.load(latest_cfe)', 'torch.load(latest_cfe, weights_only=False)')
15
+ code = code.replace('torch.load(latest_checkpoint)', 'torch.load(latest_checkpoint, weights_only=False)')
16
+
17
+ # Fix 1, 6: Update the main loop
18
+ old_loop = """ # Perform 5-fold cross-validation training
19
+ for fold in range(5):
20
+ model = CMTLNet(in_channels=3, num_classes=2, Arcm=0.5, multi=3) # Initialize the model
21
+ model_basic_CFE = torch.load(Base_CEF_model_paths[fold], weights_only=False)
22
+ model.ShareTask.load_state_dict(model_basic_CFE.state_dict())
23
+ save_name = model.name # Get the model's name
24
+ print(f"{save_name}_Fold_{fold}")
25
+ train(fold, pkl_paths) # Start training"""
26
+
27
+ new_loop = """ # Perform 5-fold cross-validation training
28
+ for fold in range(5):
29
+ import glob
30
+ import wandb
31
+ cfe_pattern = f'results/CFE/Fold_{fold}/CFE_F1_*.pkl'
32
+ cfe_files = glob.glob(cfe_pattern)
33
+ if cfe_files:
34
+ latest_cfe = max(cfe_files, key=os.path.getmtime)
35
+ print(f"✅ Loading CFE model for Fold {fold}: {latest_cfe}")
36
+ else:
37
+ raise FileNotFoundError(f"No CFE checkpoint found for Fold {fold} in {cfe_pattern}")
38
+
39
+ model = CMTLNet(in_channels=3, num_classes=2, Arcm=0.5, multi=3) # Initialize the model
40
+ model = model.to(config.device if hasattr(config, 'device') else 'cuda')
41
+ model_basic_CFE = torch.load(latest_cfe, weights_only=False)
42
+ model.ShareTask.load_state_dict(model_basic_CFE.get('model_state_dict', model_basic_CFE.state_dict()) if isinstance(model_basic_CFE, dict) else model_basic_CFE.state_dict())
43
+
44
+ save_name = getattr(model, 'name', 'UFE_UCFC')
45
+ print(f"{save_name}_Fold_{fold}")
46
+
47
+ # Initialize wandb
48
+ wandb.init(
49
+ project="CMTLNet-Training",
50
+ name=f"Step2-Fold-{fold}",
51
+ config={
52
+ 'epochs': config.epochs_s2,
53
+ 'batch_size': config.batch_size,
54
+ 'learning_rate': config.lr_self,
55
+ 'num_workers': config.n_threads,
56
+ },
57
+ reinit=True
58
+ )
59
+
60
+ train(fold, pkl_paths) # Start training
61
+ wandb.finish()"""
62
+
63
+ if old_loop in code:
64
+ code = code.replace(old_loop, new_loop)
65
+ else:
66
+ # Try regex if slight formatting difference
67
+ pattern = re.compile(r'# Perform 5-fold cross-validation training.*?train\(fold, pkl_paths\).*?# Start training', re.DOTALL)
68
+ if pattern.search(code):
69
+ code = pattern.sub(new_loop, code)
70
+
71
+ # Remove the old hardcoded paths block if it exists
72
+ old_paths = """ Base_CEF_model_paths = [
73
+ './Fold_0/CFE.pkl',
74
+ './Fold_1/CFE.pkl',
75
+ './Fold_2/CFE.pkl',
76
+ './Fold_3/CFE.pkl',
77
+ './Fold_4/CFE.pkl'
78
+ ]"""
79
+ if old_paths in code:
80
+ code = code.replace(old_paths, "")
81
+
82
+ # Fix Pandas deprecation warning if present
83
+ code = code.replace('log_1p19q.append(log_entry_1p19q, ignore_index=True)', 'pd.concat([log_1p19q, log_entry_1p19q.to_frame().T], ignore_index=True)')
84
+ code = code.replace('log_IDH.append(log_entry_IDH, ignore_index=True)', 'pd.concat([log_IDH, log_entry_IDH.to_frame().T], ignore_index=True)')
85
+ code = code.replace('log_LHG.append(log_entry_LHG, ignore_index=True)', 'pd.concat([log_LHG, log_entry_LHG.to_frame().T], ignore_index=True)')
86
+ code = code.replace('log_mean.append(log_entry_mean, ignore_index=True)', 'pd.concat([log_mean, log_entry_mean.to_frame().T], ignore_index=True)')
87
+
88
+
89
+ with open('Train_CMTLNet_Step2.py', 'w') as f:
90
+ f.write(code)
91
+ print("Initial replacements done.")
code/fix_step2_part2.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+
4
+ with open('Train_CMTLNet_Step2.py', 'r') as f:
5
+ code = f.read()
6
+
7
+ target = """ global_step = 0 # Initialize global step
8
+ best_score = -1 # Initialize best score
9
+
10
+ # Initialize DataFrames for logging
11
+ log_1p19q = pd.DataFrame(columns=[
12
+ 'epoch',
13
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
14
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
15
+ ])
16
+
17
+ log_IDH = pd.DataFrame(columns=[
18
+ 'epoch',
19
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
20
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
21
+ ])
22
+
23
+ log_LHG = pd.DataFrame(columns=[
24
+ 'epoch',
25
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
26
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
27
+ ])
28
+
29
+ log_mean = pd.DataFrame(columns=[
30
+ 'epoch',
31
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
32
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
33
+ ])
34
+
35
+ model.train() # Set model to training mode
36
+
37
+ # Initialize iterator indices
38
+ iter_index_IDH = 0
39
+ iter_index_LHG = 0
40
+
41
+ iter_IDH = iter(train_loader_IDH)
42
+ iter_LHG = iter(train_loader_LHG)
43
+
44
+ for epoch in range(config.epochs_s2):"""
45
+
46
+ replacement = """ global_step = 0 # Initialize global step
47
+ best_score = -1 # Initialize best score
48
+ start_epoch = 0
49
+ scaler = GradScaler()
50
+ save_name = getattr(model, 'name', 'UFE_UCFC')
51
+ save_path = os.path.join(config.data_dir, 'results', 'UFE_UCFC', f'Fold_{fold}')
52
+ if not os.path.exists(save_path):
53
+ os.makedirs(save_path)
54
+
55
+ # Resume logic
56
+ import glob
57
+ checkpoints = glob.glob(os.path.join(save_path, f'checkpoint_fold{fold}_epoch*.pkl'))
58
+ if checkpoints:
59
+ latest_checkpoint = max(checkpoints, key=lambda x: int(x.split('epoch')[1].split('.pkl')[0]))
60
+ print(f"Resuming from checkpoint: {latest_checkpoint}")
61
+ checkpoint = torch.load(latest_checkpoint, weights_only=False)
62
+ model.load_state_dict(checkpoint['model_state_dict'])
63
+ if 'optimizer_state_dict' in checkpoint:
64
+ optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
65
+ if 'scheduler_state_dict' in checkpoint:
66
+ scheduler.load_state_dict(checkpoint['scheduler_state_dict'])
67
+ if 'scaler_state_dict' in checkpoint:
68
+ scaler.load_state_dict(checkpoint['scaler_state_dict'])
69
+ if 'global_step' in checkpoint:
70
+ global_step = checkpoint['global_step']
71
+ if 'best_f1' in checkpoint:
72
+ best_score = checkpoint['best_f1']
73
+ if 'epoch' in checkpoint:
74
+ start_epoch = checkpoint['epoch'] + 1
75
+
76
+ # Initialize DataFrames for logging
77
+ log_1p19q = pd.DataFrame(columns=[
78
+ 'epoch',
79
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
80
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
81
+ ])
82
+
83
+ log_IDH = pd.DataFrame(columns=[
84
+ 'epoch',
85
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
86
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
87
+ ])
88
+
89
+ log_LHG = pd.DataFrame(columns=[
90
+ 'epoch',
91
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
92
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
93
+ ])
94
+
95
+ log_mean = pd.DataFrame(columns=[
96
+ 'epoch',
97
+ 'Train_loss', 'Train_Accuracy', 'Train_F1',
98
+ 'Val_loss', 'Val_Accuracy', 'Val_F1'
99
+ ])
100
+
101
+ model.train() # Set model to training mode
102
+
103
+ # Initialize iterator indices
104
+ iter_index_IDH = 0
105
+ iter_index_LHG = 0
106
+
107
+ iter_IDH = iter(train_loader_IDH)
108
+ iter_LHG = iter(train_loader_LHG)
109
+
110
+ for epoch in range(start_epoch, config.epochs_s2):"""
111
+
112
+ if target in code:
113
+ code = code.replace(target, replacement)
114
+ else:
115
+ print("Failed to replace target 1")
116
+
117
+ with open('Train_CMTLNet_Step2.py', 'w') as f:
118
+ f.write(code)
119
+ print("Part 2 replacements done.")
code/fix_step2_part3.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+
4
+ with open('Train_CMTLNet_Step2.py', 'r') as f:
5
+ code = f.read()
6
+
7
+ target = """ # Forward pass (now receives risk_scores)
8
+ (out_cls_list_UFE, out_cls_labels_UFE,
9
+ out_cls_list_UCFC, out_cls_labels_UCFC, risk_scores) = model(combined_input, label_list, condition)
10
+
11
+ # --- CALCULATE COX LOSS ---
12
+ # Mask out patients who don't have survival data (time == 0)
13
+ valid_mask = combined_times > 0
14
+ if valid_mask.sum() >= 2: # Cox loss needs at least a pair to rank
15
+ loss_surv = cox_ph_loss(risk_scores[valid_mask], combined_times[valid_mask], combined_events[valid_mask])
16
+ else:
17
+ loss_surv = torch.tensor(0.0, device=risk_scores.device, requires_grad=True)
18
+
19
+ # Classification losses
20
+ loss_cls_U1 = cross_entropy_loss(out_cls_list_UFE[0], out_cls_labels_UFE[0])
21
+ loss_cls_U2 = cross_entropy_loss(out_cls_list_UFE[1], out_cls_labels_UFE[1])
22
+ loss_cls_U3 = cross_entropy_loss(out_cls_list_UFE[2], out_cls_labels_UFE[2])
23
+ loss_cls_1 = cross_entropy_loss(out_cls_list_UCFC[0], out_cls_labels_UCFC[0])
24
+ loss_cls_2 = cross_entropy_loss(out_cls_list_UCFC[1], out_cls_labels_UCFC[1])
25
+ loss_cls_3 = cross_entropy_loss(out_cls_list_UCFC[2], out_cls_labels_UCFC[2])
26
+
27
+ # Total loss (weighing survival by 0.5 so it doesn't overpower classification)
28
+ total_loss = loss_cls_U1 + loss_cls_U2 + loss_cls_U3 + loss_cls_1 + loss_cls_2 + loss_cls_3 + (0.5 * loss_surv)
29
+
30
+ # Backward pass
31
+ optimizer.zero_grad()
32
+ total_loss.backward()
33
+ optimizer.step()"""
34
+
35
+ replacement = """ # Forward pass with AMP
36
+ with autocast():
37
+ (out_cls_list_UFE, out_cls_labels_UFE,
38
+ out_cls_list_UCFC, out_cls_labels_UCFC, risk_scores) = model(combined_input, label_list, condition)
39
+
40
+ # --- CALCULATE COX LOSS ---
41
+ valid_mask = combined_times > 0
42
+ if valid_mask.sum() >= 2:
43
+ loss_surv = cox_ph_loss(risk_scores[valid_mask], combined_times[valid_mask], combined_events[valid_mask])
44
+ else:
45
+ loss_surv = torch.tensor(0.0, device=risk_scores.device, requires_grad=True)
46
+
47
+ loss_cls_U1 = cross_entropy_loss(out_cls_list_UFE[0], out_cls_labels_UFE[0])
48
+ loss_cls_U2 = cross_entropy_loss(out_cls_list_UFE[1], out_cls_labels_UFE[1])
49
+ loss_cls_U3 = cross_entropy_loss(out_cls_list_UFE[2], out_cls_labels_UFE[2])
50
+ loss_cls_1 = cross_entropy_loss(out_cls_list_UCFC[0], out_cls_labels_UCFC[0])
51
+ loss_cls_2 = cross_entropy_loss(out_cls_list_UCFC[1], out_cls_labels_UCFC[1])
52
+ loss_cls_3 = cross_entropy_loss(out_cls_list_UCFC[2], out_cls_labels_UCFC[2])
53
+
54
+ total_loss = loss_cls_U1 + loss_cls_U2 + loss_cls_U3 + loss_cls_1 + loss_cls_2 + loss_cls_3 + (0.5 * loss_surv)
55
+
56
+ # Backward pass with AMP
57
+ optimizer.zero_grad()
58
+ scaler.scale(total_loss).backward()
59
+ scaler.step(optimizer)
60
+ scaler.update()"""
61
+
62
+ if target in code:
63
+ code = code.replace(target, replacement)
64
+ else:
65
+ print("Target 3 not found.")
66
+
67
+ target2 = """ # Define save path
68
+ save_path = os.path.join(config.data_dir, 'results', str(save_name), f'Fold_{fold}')
69
+ if not os.path.exists(save_path):
70
+ os.makedirs(save_path)"""
71
+
72
+ if target2 in code:
73
+ code = code.replace(target2, "")
74
+ else:
75
+ print("Target 4 not found.")
76
+
77
+ with open('Train_CMTLNet_Step2.py', 'w') as f:
78
+ f.write(code)
79
+ print("Part 3 replacements done.")
code/fix_step2_part4.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+
4
+ with open('Train_CMTLNet_Step2.py', 'r') as f:
5
+ code = f.read()
6
+
7
+ target = """ # Save the best model based on F1 score
8
+ if epoch >= config.save_epoch:
9
+ if current_f1 > best_score:
10
+ save_config = {
11
+ 'name': save_name,
12
+ 'save_dir': save_path,
13
+ 'global_step': global_step,
14
+ 'Test_F1': current_f1
15
+ }
16
+ save_model(model=model, config=save_config)
17
+ best_score = current_f1
18
+
19
+ # Update the best score if current F1 is better
20
+ if current_f1 > best_score:
21
+ best_score = current_f1
22
+
23
+ # Step the scheduler based on the best score
24
+ scheduler.step(best_score)"""
25
+
26
+ replacement = """ # Save the best model based on F1 score
27
+ if epoch >= config.save_epoch:
28
+ if current_f1 > best_score:
29
+ save_config = {
30
+ 'name': save_name,
31
+ 'save_dir': save_path,
32
+ 'global_step': global_step,
33
+ 'Test_F1': current_f1
34
+ }
35
+ save_model(model=model, config=save_config)
36
+
37
+ # Reconstruct path generated by save_model to upload it
38
+ f1_percentage = current_f1 * 100
39
+ best_path = os.path.join(save_path, f"{save_name}_F1_{f1_percentage:.2f}_step_{global_step}.pkl")
40
+
41
+ best_model_name = f'best_model_fold{fold}.pkl'
42
+ best_model_path = os.path.join(save_path, best_model_name)
43
+ import shutil
44
+ if os.path.exists(best_path):
45
+ shutil.copy(best_path, best_model_path)
46
+
47
+ # Upload best model to W&B
48
+ if wandb.run is not None:
49
+ wandb.save(best_model_path)
50
+
51
+ # Upload best model to Hugging Face
52
+ hf_token = os.environ.get("HF_TOKEN")
53
+ if hf_token and os.path.exists(best_model_path):
54
+ try:
55
+ from huggingface_hub import upload_file
56
+ upload_file(
57
+ path_or_fileobj=best_model_path,
58
+ path_in_repo=f"best_models/Fold_{fold}/{best_model_name}",
59
+ repo_id="jainamdedhia/cmtlnet-training",
60
+ repo_type="dataset",
61
+ token=hf_token,
62
+ )
63
+ print(f"☁️ Best model uploaded to Hugging Face: {best_model_name}")
64
+ except Exception as e:
65
+ print(f"⚠️ Hugging Face best model upload failed: {e}")
66
+
67
+ best_score = current_f1
68
+
69
+ # Update the best score if current F1 is better
70
+ if current_f1 > best_score:
71
+ best_score = current_f1
72
+
73
+ # Step the scheduler based on the best score
74
+ scheduler.step(best_score)
75
+
76
+ # ===== LIGHT CHECKPOINT EVERY 5 EPOCHS =====
77
+ if epoch % 5 == 0 and epoch > 0:
78
+ light_checkpoint_path = os.path.join(save_path, f'checkpoint_fold{fold}_epoch{epoch}.pkl')
79
+ torch.save({
80
+ 'epoch': epoch,
81
+ 'fold': fold,
82
+ 'model_state_dict': model.state_dict(),
83
+ 'optimizer_state_dict': optimizer.state_dict(),
84
+ 'scheduler_state_dict': scheduler.state_dict(),
85
+ 'scaler_state_dict': scaler.state_dict(),
86
+ 'best_f1': best_score,
87
+ 'global_step': global_step
88
+ }, light_checkpoint_path)
89
+ print(f"✅ Light checkpoint saved locally: {light_checkpoint_path}")
90
+
91
+ # Upload to W&B
92
+ if wandb.run is not None:
93
+ wandb.save(light_checkpoint_path)
94
+ print(f"☁️ Uploaded to W&B: {light_checkpoint_path}")
95
+
96
+ # Upload to Hugging Face
97
+ hf_token = os.environ.get("HF_TOKEN")
98
+ if hf_token:
99
+ try:
100
+ from huggingface_hub import upload_file
101
+ filename_only = os.path.basename(light_checkpoint_path)
102
+ upload_file(
103
+ path_or_fileobj=light_checkpoint_path,
104
+ path_in_repo=f"checkpoints/{filename_only}",
105
+ repo_id="jainamdedhia/cmtlnet-training",
106
+ repo_type="dataset",
107
+ token=hf_token,
108
+ )
109
+ print(f"☁️ Uploaded to Hugging Face: {light_checkpoint_path}")
110
+ except Exception as e:
111
+ print(f"⚠️ Hugging Face upload failed: {e}")
112
+ else:
113
+ print("ℹ️ HF_TOKEN not set. Skipping Hugging Face upload.")
114
+ # ===== END LIGHT CHECKPOINT =====
115
+
116
+ # Log to W&B
117
+ if wandb.run is not None:
118
+ wandb.log({
119
+ "Train/Mean_Loss": metrics_train_mean[0],
120
+ "Train/Mean_Accuracy": metrics_train_mean[1],
121
+ "Train/Mean_F1": metrics_train_mean[2],
122
+ "Test/Mean_Loss": metrics_test_mean[0],
123
+ "Test/Mean_Accuracy": metrics_test_mean[1],
124
+ "Test/Mean_F1": metrics_test_mean[2],
125
+ "Epoch": epoch,
126
+ "Learning_Rate": current_lr,
127
+ "Global_Step": global_step
128
+ })
129
+
130
+ # Safely empty cache at the end of the epoch
131
+ gc.collect()
132
+ torch.cuda.empty_cache()"""
133
+
134
+ if target in code:
135
+ code = code.replace(target, replacement)
136
+ else:
137
+ print("Target 5 not found.")
138
+
139
+ with open('Train_CMTLNet_Step2.py', 'w') as f:
140
+ f.write(code)
141
+ print("Part 4 replacements done.")
code/preprocessing/1_registration.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ANTsPy (https://github.com/ANTsX/ANTsPy)
2
+ import ants
3
+
4
+ def registration_function(fixed_image_path, moving_image_path, output_image_path):
5
+ """
6
+ Registers a moving image to a fixed image using affine transformation and saves the registered image.
7
+
8
+ Parameters:
9
+ fixed_image_path (str): Path to the fixed image (reference image).
10
+ moving_image_path (str): Path to the moving image (image to be registered).
11
+ output_image_path (str): Path where the registered image will be saved.
12
+ """
13
+ # Step 1: Load images using ANTs
14
+ fixed_image = ants.image_read(fixed_image_path) # Read the fixed (reference) image
15
+ moving_image = ants.image_read(moving_image_path) # Read the moving image
16
+
17
+ '''
18
+ ANTs registration function returns a dictionary containing:
19
+ - warpedmovout: The moving image registered to the fixed image
20
+ - warpedfixout: The fixed image registered to the moving image
21
+ - fwdtransforms: Transformation field from moving to fixed image
22
+ - invtransforms: Transformation field from fixed to moving image
23
+
24
+ Available transform types:
25
+ - Rigid: Rigid transformation (translation + rotation)
26
+ - Affine: Affine transformation (rigid + scaling)
27
+ - ElasticSyN: Elastic SyN transformation (affine + nonlinear with MI as the criterion)
28
+ - SyN: SyN transformation (affine + nonlinear with MI as the criterion)
29
+ - SyNCC: SyN transformation (affine + nonlinear with CC as the criterion)
30
+ '''
31
+
32
+ # Step 2: Perform image registration (using affine transformation)
33
+ registration_result = ants.registration(fixed=fixed_image, moving=moving_image, type_of_transform='Affine')
34
+
35
+ # Step 3: Apply the forward transformation to the moving image to get the registered image
36
+ registered_image = ants.apply_transforms(
37
+ fixed=fixed_image, # Fixed image (reference)
38
+ moving=moving_image, # Moving image (to be registered)
39
+ transformlist=registration_result['fwdtransforms'], # Transformation field
40
+ interpolator="linear" # Interpolation method for resampling
41
+ )
42
+
43
+ # Step 4: Ensure the registered image matches the fixed image's properties (direction, origin, spacing)
44
+ registered_image.set_direction(fixed_image.direction)
45
+ registered_image.set_origin(fixed_image.origin)
46
+ registered_image.set_spacing(fixed_image.spacing)
47
+
48
+ # Step 5: Save the registered image
49
+ ants.image_write(registered_image, output_image_path)
50
+
51
+ print("Registration complete. Registered image saved to:", output_image_path)
52
+
53
+
54
+ if __name__ == '__main__':
55
+ # Define the paths for fixed and moving images, and the output paths for the registered images
56
+ fixed_image_path = "./regdata/spgr_unstrip_lps_b.nii.gz"
57
+
58
+ moving_image_path1 = "./regdata/LGG-637/T1C.nii.gz"
59
+ output_image_path1 = "./regdata/LGG-637/registration_T1C.nii.gz"
60
+
61
+ moving_image_path2 = "./regdata/LGG-637/T2W.nii.gz"
62
+ output_image_path2 = "./regdata/LGG-637/registration_T2W.nii.gz"
63
+
64
+ # Perform registration for the first moving image (T1C)
65
+ registration_function(fixed_image_path, moving_image_path1, output_image_path1)
66
+
67
+ # Perform registration for the second moving image (T2w) using the registered T1C image as the fixed image
68
+ registration_function(output_image_path1, moving_image_path2, output_image_path2)
code/preprocessing/2_cutbackground.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import nibabel as nib
4
+ from os import path
5
+
6
+ # Read files from the specified directory at a given level (num).
7
+ def readDir(path, num):
8
+ """
9
+ Reads the directory and returns the filenames from the specified level (num).
10
+ """
11
+ im = []
12
+ k = 0
13
+ for root in os.walk(path):
14
+ if k == 0:
15
+ im.append(root[num])
16
+ k = k+1
17
+ if k == 1:
18
+ continue
19
+ return im
20
+
21
+ # Recursively get all filenames in a directory and its subdirectories.
22
+ def get_filenames(dirpath, filenames):
23
+ """
24
+ Recursively get all filenames in a directory and its subdirectories.
25
+ """
26
+ if not path.isabs(dirpath):
27
+ dirpath = path.abspath(dirpath)
28
+ for pathname, dirs, files in os.walk(dirpath):
29
+ if files:
30
+ for f in files:
31
+ filenames.append(path.join(pathname, f))
32
+ if dirs:
33
+ for dir_ in dirs:
34
+ get_filenames(path.join(pathname, dir_), filenames)
35
+
36
+ # Save a numpy array as a NIfTI image
37
+ def save_nii(arr, file_path, affine):
38
+ """
39
+ Save a numpy array as a NIfTI image.
40
+ """
41
+ nib.Nifti1Image(arr, affine).to_filename(file_path)
42
+
43
+ # Load a NIfTI file and return its data and affine transformation matrix
44
+ def load_nii_affine(filename):
45
+ """
46
+ Loads a NIfTI file and returns its data and affine transformation matrix.
47
+ """
48
+ if not os.path.exists(filename):
49
+ return np.array([1])
50
+ nii = nib.load(filename)
51
+ data = nii.get_fdata() # get_fdata() is preferred over get_data() in newer nibabel versions
52
+ affine = nii.affine
53
+ nii.uncache()
54
+ return data, affine
55
+
56
+ # Calculate the bounding box of a mask (region of interest)
57
+ def get_bbox_from_mask(mask, outside_value=0):
58
+ """
59
+ Calculate the bounding box of a mask (region of interest).
60
+ """
61
+ mask_voxel_coords = np.where(mask != outside_value)
62
+ minzidx = int(np.min(mask_voxel_coords[0]))
63
+ maxzidx = int(np.max(mask_voxel_coords[0])) + 1
64
+ minxidx = int(np.min(mask_voxel_coords[1]))
65
+ maxxidx = int(np.max(mask_voxel_coords[1])) + 1
66
+ minyidx = int(np.min(mask_voxel_coords[2]))
67
+ maxyidx = int(np.max(mask_voxel_coords[2])) + 1
68
+ return [minzidx, maxzidx], [minxidx, maxxidx], [minyidx, maxyidx]
69
+
70
+ # Crop the image to the given bounding box
71
+ def crop_to_bbox(image, bbox):
72
+ """
73
+ Crop the image to the given bounding box.
74
+ """
75
+ assert len(image.shape) == 3, "Only supports 3D images."
76
+ resizer = (slice(bbox[0][0], bbox[0][1]), slice(bbox[1][0], bbox[1][1]), slice(bbox[2][0], bbox[2][1]))
77
+ return image[resizer]
78
+
79
+ # Extract and crop the data from images
80
+ def Crop_data():
81
+ """
82
+ Crop the images in the specified directory and save the cropped images to the target path.
83
+ """
84
+ import warnings
85
+ warnings.filterwarnings("ignore")
86
+ all_file_names = readDir(original_img_path, 1)[0]
87
+
88
+ img_size_list = []
89
+ for img_index in range(len(all_file_names)):
90
+ print(f'== Processing {img_index + 1}/{len(all_file_names)}: {all_file_names[img_index]} ==')
91
+
92
+ # File paths
93
+ img_path_T1 = original_img_path + all_file_names[img_index] + '/' + all_file_names[img_index] + '_t1.nii.gz'
94
+ img_path_T1C = original_img_path + all_file_names[img_index] + '/' + all_file_names[img_index] + '_t1ce.nii.gz'
95
+ img_path_T2 = original_img_path + all_file_names[img_index] + '/' + all_file_names[img_index] + '_t2.nii.gz'
96
+ img_path_FLAIR = original_img_path + all_file_names[img_index] + '/' + all_file_names[img_index] + '_flair.nii.gz'
97
+ img_path_seg = original_img_path + all_file_names[img_index] + '/' + all_file_names[img_index] + '_seg.nii.gz'
98
+
99
+ # Load data
100
+ nii_data_1, affine = load_nii_affine(img_path_T1)
101
+ nii_data_2, affine_2 = load_nii_affine(img_path_T1C)
102
+ nii_data_3, affine_3 = load_nii_affine(img_path_T2)
103
+ nii_data_4, affine_4 = load_nii_affine(img_path_FLAIR)
104
+ nii_seg, affine_seg = load_nii_affine(img_path_seg)
105
+
106
+ # Calculate bounding box
107
+ combined_image = nii_data_1 + nii_data_2 + nii_data_3 + nii_data_4
108
+ bbox = get_bbox_from_mask(combined_image)
109
+
110
+ # Crop images
111
+ cropped_1 = crop_to_bbox(nii_data_1, bbox)
112
+ cropped_2 = crop_to_bbox(nii_data_2, bbox)
113
+ cropped_3 = crop_to_bbox(nii_data_3, bbox)
114
+ cropped_4 = crop_to_bbox(nii_data_4, bbox)
115
+ cropped_seg = crop_to_bbox(nii_seg, bbox)
116
+ cropped_seg = (cropped_seg > 0).astype(np.uint8)
117
+
118
+ # Get cropped image size
119
+ img_size = cropped_1.shape
120
+
121
+ # Save paths
122
+ save_path_T1 = save_img_path + all_file_names[img_index] + '/T1.nii'
123
+ save_path_T1C = save_img_path + all_file_names[img_index] + '/T1C.nii'
124
+ save_path_T2 = save_img_path + all_file_names[img_index] + '/T2.nii'
125
+ save_path_FLAIR = save_img_path + all_file_names[img_index] + '/FLAIR.nii'
126
+ save_path_seg = save_img_path + all_file_names[img_index] + '/mask.nii'
127
+
128
+ if not os.path.exists(save_img_path + all_file_names[img_index] + '/'):
129
+ os.makedirs(save_img_path + all_file_names[img_index] + '/')
130
+
131
+ # Save cropped images
132
+ save_nii(cropped_1.astype(np.uint16), save_path_T1, affine)
133
+ save_nii(cropped_2.astype(np.uint16), save_path_T1C, affine)
134
+ save_nii(cropped_3.astype(np.uint16), save_path_T2, affine)
135
+ save_nii(cropped_4.astype(np.uint16), save_path_FLAIR, affine)
136
+ save_nii(cropped_seg.astype(np.uint8), save_path_seg, affine_seg)
137
+
138
+ img_size_list.append(img_size)
139
+
140
+ # Save the crop sizes of all images
141
+ np.save(save_crop_size_path + 'crop_size.npy', img_size_list)
142
+ return all_file_names
143
+
144
+ def get_max_size():
145
+ img_size_list = np.load(save_crop_size_path + 'crop_size.npy')
146
+ size_1 = np.zeros((len(img_size_list)))
147
+ size_2 = np.zeros((len(img_size_list)))
148
+ size_3 = np.zeros((len(img_size_list)))
149
+ for size_temp in range(len(img_size_list)):
150
+ size_1[size_temp] = int(img_size_list[size_temp][0])
151
+ size_2[size_temp] = int(img_size_list[size_temp][1])
152
+ size_3[size_temp] = int(img_size_list[size_temp][2])
153
+ print(np.max(size_1), np.max(size_2), np.max(size_3))
154
+
155
+ # 3D padding
156
+ def Padding3d(data, padding_shape):
157
+ """
158
+ Add padding to a 3D image.
159
+ """
160
+ padding_h, padding_w, padding_d = (np.array(padding_shape) - np.array(np.shape(data))) // 2
161
+
162
+ padding_T = np.zeros([padding_h, np.shape(data)[1], np.shape(data)[2]], dtype=np.uint8)
163
+ padding_B = np.zeros([padding_shape[0] - padding_h - np.shape(data)[0],
164
+ np.shape(data)[1], np.shape(data)[2]], dtype=np.uint8)
165
+ H_data = np.concatenate([padding_T, data, padding_B], 0)
166
+
167
+ padding_L = np.zeros([np.shape(H_data)[0], padding_w, np.shape(H_data)[2]], dtype=np.uint8)
168
+ padding_R = np.zeros([np.shape(H_data)[0],
169
+ padding_shape[1] - padding_w - np.shape(H_data)[1], np.shape(H_data)[2]], dtype=np.uint8)
170
+ W_data = np.concatenate([padding_L, H_data, padding_R], 1)
171
+
172
+ padding_F = np.zeros([np.shape(W_data)[0], np.shape(W_data)[1], padding_d], dtype=np.uint8)
173
+ padding_B = np.zeros([np.shape(W_data)[0], np.shape(W_data)[1], padding_shape[2] - padding_d - np.shape(W_data)[2]],
174
+ dtype=np.uint8)
175
+ data = np.concatenate([padding_F, W_data, padding_B], 2)
176
+
177
+ return data
178
+
179
+ # Pad the images with zeros and save them to the target directory.
180
+ def Padding_data(all_file_names, padding_shape=(160, 192, 160)):
181
+ """
182
+ Pad the images with zeros and save them to the target directory.
183
+ """
184
+ img_size_list = np.load(save_crop_size_path + 'crop_size.npy', allow_pickle=True)
185
+ img_index = 0
186
+
187
+ for img_size in img_size_list:
188
+ print(f'== Padding {img_index + 1}/{len(img_size_list)} ==')
189
+
190
+ # Get file paths
191
+ img_path_T1 = save_img_path + all_file_names[img_index] + '/T1.nii'
192
+ img_path_T1C = save_img_path + all_file_names[img_index] + '/T1C.nii'
193
+ img_path_T2 = save_img_path + all_file_names[img_index] + '/T2.nii'
194
+ img_path_FLAIR = save_img_path + all_file_names[img_index] + '/FLAIR.nii'
195
+ img_path_seg = save_img_path + all_file_names[img_index] + '/mask.nii'
196
+
197
+ # Load data
198
+ nii_data_1, affine = load_nii_affine(img_path_T1)
199
+ nii_data_2, affine_2 = load_nii_affine(img_path_T1C)
200
+ nii_data_3, affine_3 = load_nii_affine(img_path_T2)
201
+ nii_data_4, affine_4 = load_nii_affine(img_path_FLAIR)
202
+ nii_seg, affine_seg = load_nii_affine(img_path_seg)
203
+
204
+ # Perform padding
205
+ padded_1 = Padding3d(nii_data_1, padding_shape)
206
+ padded_2 = Padding3d(nii_data_2, padding_shape)
207
+ padded_3 = Padding3d(nii_data_3, padding_shape)
208
+ padded_4 = Padding3d(nii_data_4, padding_shape)
209
+ padded_seg = Padding3d(nii_seg, padding_shape)
210
+
211
+ if not os.path.exists(save_img_path_final + all_file_names[img_index] + '/'):
212
+ os.makedirs(save_img_path_final + all_file_names[img_index] + '/')
213
+
214
+ # Save padded images
215
+ save_nii(padded_1.astype(np.uint16), save_img_path_final + all_file_names[img_index] + '/T1.nii', affine)
216
+ save_nii(padded_2.astype(np.uint16), save_img_path_final + all_file_names[img_index] + '/T1C.nii', affine_2)
217
+ save_nii(padded_3.astype(np.uint16), save_img_path_final + all_file_names[img_index] + '/T2.nii', affine_3)
218
+ save_nii(padded_4.astype(np.uint16), save_img_path_final + all_file_names[img_index] + '/FLAIR.nii', affine_4)
219
+ save_nii(padded_seg.astype(np.uint8), save_img_path_final + all_file_names[img_index] + '/mask.nii', affine_seg)
220
+
221
+ img_index += 1
222
+
223
+ if __name__ == '__main__':
224
+ # File path definitions
225
+ original_img_path = './cropdata/beforedata/' # Path to the original images
226
+ save_img_path = './cropdata/aftercrop/' # Path to save cropped images
227
+ save_crop_size_path = './cropdata/' # Path to save crop sizes
228
+ save_img_path_final = './cropdata/afterpadding/' # Path to save padded images
229
+
230
+ # Step 1: Crop out the black borders from the data
231
+ all_file_names = Crop_data() # Calls the Crop_data function to crop images
232
+
233
+ # Step 2: Verify if the maximum size in the data is smaller than (160, 192, 160)
234
+ get_max_size() # Calls the get_max_size function to check the maximum size in the data
235
+
236
+ # Step 3: Add padding with zero values and zero slices to ensure each axis is a multiple of 3 or 2
237
+ # The default padding size is (160, 192, 160)
238
+ Padding_data(all_file_names) # Calls the Padding_data function to add padding to the images
239
+
code/probe_fc_dim.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, sys
2
+ sys.path.append('.')
3
+ import config
4
+
5
+ from model.CMTLNet import CMTLNet
6
+
7
+ model = CMTLNet(in_channels=3, num_classes=2, Arcm=0.5, multi=3).to('cpu')
8
+
9
+ # Simulate a small batch to see the Fc dimension
10
+ dummy_input = torch.zeros(2, 3, 64, 64, 64) # typical shape
11
+ with torch.no_grad():
12
+ Fl, Fc = model.ShareTask.get_Sharefeatures(dummy_input)
13
+ print(f"Fc shape: {Fc.shape}")
14
+ risk_features = model.avgpool(Fc)
15
+ risk_features = torch.flatten(risk_features, 1)
16
+ print(f"risk_features shape after pool+flatten: {risk_features.shape}")
code/survival_dataset.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import os
3
+ import torch
4
+ from torch.utils.data import Dataset
5
+
6
+ class SurvivalDataset(Dataset):
7
+ def __init__(self, csv_file, root_dir):
8
+ # Using the correct filename you just provided
9
+ self.metadata = pd.read_csv(csv_file)
10
+ self.root_dir = root_dir
11
+
12
+ def __len__(self):
13
+ return len(self.metadata)
14
+
15
+ def __getitem__(self, idx):
16
+ # 1. Get the patient ID
17
+ patient_id = self.metadata.iloc[idx]['ID']
18
+
19
+ # 2. IMPORTANT: Check your folder structure on the D: drive.
20
+ # If your folders are named just "UCSF-PDGM-004" instead of "UCSF-PDGM-004_nifti",
21
+ # remove the "_nifti" from the line below.
22
+ img_folder = os.path.join(self.root_dir, patient_id)
23
+
24
+ # 3. Load your T1c path
25
+ t1c_path = os.path.join(img_folder, f"{patient_id}_T1c.nii.gz")
26
+
27
+ # 4. Get your Survival Targets
28
+ survival_time = self.metadata.iloc[idx]['OS']
29
+ event_status = self.metadata.iloc[idx]['1-dead 0-alive']
30
+
31
+ return {
32
+ 't1c_path': t1c_path,
33
+ 'time': torch.tensor(float(survival_time)),
34
+ 'event': torch.tensor(float(event_status))
35
+ }
36
+
37
+ # Quick Test
38
+ dataset = SurvivalDataset("clinicaldata.csv", r"D:\jainam\UCSF-PDGM-v5")
39
+ print(dataset[0])
code/survivalstandalone/__init__.py ADDED
File without changes
code/survivalstandalone/datadownload.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ download_from_hf.py
3
+
4
+ Run this on your new (i9/3080ti) laptop to pull down the trimmed UCSF-PDGM
5
+ dataset you uploaded to HuggingFace (unknownBrain/ucsf).
6
+
7
+ Install first:
8
+ pip install -U huggingface_hub
9
+
10
+ If the dataset repo is private, also run:
11
+ huggingface-cli login
12
+
13
+ Run in two steps:
14
+ python download_from_hf.py list -> just prints file list/structure
15
+ python download_from_hf.py download -> actually downloads everything
16
+ """
17
+
18
+ import sys
19
+ from huggingface_hub import HfApi, snapshot_download
20
+
21
+ HF_REPO_ID = "unknownBrain/ucsf"
22
+ LOCAL_DIR = r"D:\jainam\UCSF-PDGM-v5" # where you want it locally
23
+
24
+ api = HfApi()
25
+
26
+
27
+ def list_files():
28
+ files = api.list_repo_files(repo_id=HF_REPO_ID, repo_type="dataset")
29
+ print(f"total files: {len(files)}")
30
+ for f in files[:30]:
31
+ print(" ", f)
32
+ if len(files) > 30:
33
+ print(f" ... and {len(files) - 30} more")
34
+ # This tells you whether folder structure survived the upload
35
+ # (e.g. 'UCSF-PDGM-004/UCSF-PDGM-004_T1c.nii.gz') or got flattened
36
+ # (e.g. 'UCSF-PDGM-004_T1c.nii.gz' with no subfolder) -- update
37
+ # dataset.py's build_records() path template to match whichever it is.
38
+
39
+
40
+ def download():
41
+ path = snapshot_download(
42
+ repo_id=HF_REPO_ID,
43
+ repo_type="dataset",
44
+ local_dir=LOCAL_DIR,
45
+ local_dir_use_symlinks=False, # actual files, not symlinks -- safer on Windows
46
+ # allow_patterns=["*_T1c.nii.gz", "*_T2.nii.gz", "*_tumor_segmentation.nii.gz"],
47
+ # ^ uncomment + edit if you only want specific modalities right now
48
+ )
49
+ print("Downloaded to:", path)
50
+
51
+
52
+ if __name__ == "__main__":
53
+ mode = sys.argv[1] if len(sys.argv) > 1 else "list"
54
+ if mode == "list":
55
+ list_files()
56
+ elif mode == "download":
57
+ download()
58
+ else:
59
+ print("usage: python download_from_hf.py [list|download]")
code/survivalstandalone/preprocess_ucsf.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ preprocess_ucsf.py
3
+
4
+ Adapts the repo's 1_registration.py + 2_cutbackground.py pipeline to the
5
+ UCSF-PDGM file naming you actually have (T1c, T2, FLAIR, tumor_segmentation).
6
+
7
+ Pipeline per subject (matches the paper's described preprocessing):
8
+ 1. Register T1c -> SRI24 atlas (Affine)
9
+ 2. Register T2 -> registered T1c (Affine) [fresh registration, like the repo script]
10
+ 3. Register FLAIR -> registered T1c (Affine)
11
+ 4. Warp tumor_segmentation using T1c's transform (nearestNeighbor -- masks
12
+ must NOT be intensity-registered, they ride along on T1c's transform)
13
+ 5. Crop to combined nonzero bounding box (T1c+T2+FLAIR), then zero-pad to
14
+ (160, 192, 160)
15
+
16
+ This is SLOW (ANTs registration is CPU-bound). Test on a handful of subjects
17
+ first with LIMIT below before committing to the full 500.
18
+
19
+ Requires: pip install antspyx nibabel numpy
20
+ """
21
+
22
+ import os
23
+ import glob
24
+ import numpy as np
25
+ import ants
26
+ import nibabel as nib
27
+
28
+ # ---- EDIT THESE FOR YOUR MACHINE ----
29
+ RAW_ROOT = r"D:\jainam\UCSF-PDGM-v5" # where datadownload.py put the raw files
30
+ OUT_ROOT = r"D:\jainam\UCSF-PDGM-v5-preprocessed" # where final preprocessed volumes go
31
+ ATLAS_PATH = r"D:\jainam\CMTLNet\CMTLNet\preprocessing\regdata\spgr_unstrip_lps_b.nii.gz"
32
+ TARGET_SHAPE = (160, 192, 160)
33
+ LIMIT = None # set to None to run all subjects; test with a small number first!
34
+ # --------------------------------------
35
+
36
+
37
+ def get_bbox_from_mask(mask, outside_value=0):
38
+ coords = np.where(mask != outside_value)
39
+ return (
40
+ [int(coords[0].min()), int(coords[0].max()) + 1],
41
+ [int(coords[1].min()), int(coords[1].max()) + 1],
42
+ [int(coords[2].min()), int(coords[2].max()) + 1],
43
+ )
44
+
45
+
46
+ def crop_to_bbox(image, bbox):
47
+ resizer = tuple(slice(b[0], b[1]) for b in bbox)
48
+ return image[resizer]
49
+
50
+
51
+ def pad_to_shape(arr, target_shape):
52
+ """Pad with zeros to target_shape (assumes arr is <= target on every axis
53
+ after the bbox crop; if not, center-crop the overflow first)."""
54
+ out = np.zeros(target_shape, dtype=arr.dtype)
55
+ src_slices, dst_slices = [], []
56
+ for s, t in zip(arr.shape, target_shape):
57
+ if s <= t:
58
+ pad_start = (t - s) // 2
59
+ src_slices.append(slice(0, s))
60
+ dst_slices.append(slice(pad_start, pad_start + s))
61
+ else:
62
+ start = (s - t) // 2
63
+ src_slices.append(slice(start, start + t))
64
+ dst_slices.append(slice(0, t))
65
+ out[tuple(dst_slices)] = arr[tuple(src_slices)]
66
+ return out
67
+
68
+
69
+ def register_subject(sid: str, atlas):
70
+ raw_folder = os.path.join(RAW_ROOT, f"{sid}_nifti")
71
+ t1c_path = os.path.join(raw_folder, f"{sid}_T1c.nii.gz")
72
+ t2_path = os.path.join(raw_folder, f"{sid}_T2.nii.gz")
73
+ flair_path = os.path.join(raw_folder, f"{sid}_FLAIR.nii.gz")
74
+ mask_path = os.path.join(raw_folder, f"{sid}_tumor_segmentation.nii.gz")
75
+
76
+ if not all(os.path.exists(p) for p in [t1c_path, t2_path, flair_path, mask_path]):
77
+ print(f" [skip] {sid}: missing one or more raw files")
78
+ return
79
+
80
+ # 1. T1c -> atlas
81
+ t1c = ants.image_read(t1c_path)
82
+ reg_t1c = ants.registration(fixed=atlas, moving=t1c, type_of_transform="Affine")
83
+ t1c_warped = reg_t1c["warpedmovout"]
84
+
85
+ # 2. T2 -> registered T1c
86
+ t2 = ants.image_read(t2_path)
87
+ reg_t2 = ants.registration(fixed=t1c_warped, moving=t2, type_of_transform="Affine")
88
+ t2_warped = reg_t2["warpedmovout"]
89
+
90
+ # 3. FLAIR -> registered T1c
91
+ flair = ants.image_read(flair_path)
92
+ reg_flair = ants.registration(fixed=t1c_warped, moving=flair, type_of_transform="Affine")
93
+ flair_warped = reg_flair["warpedmovout"]
94
+
95
+ # 4. mask rides on T1c's transform, nearest-neighbor (no independent registration)
96
+ mask = ants.image_read(mask_path)
97
+ mask_warped = ants.apply_transforms(
98
+ fixed=atlas, moving=mask,
99
+ transformlist=reg_t1c["fwdtransforms"],
100
+ interpolator="nearestNeighbor",
101
+ )
102
+
103
+ # convert to numpy for crop/pad
104
+ t1c_np = t1c_warped.numpy()
105
+ t2_np = t2_warped.numpy()
106
+ flair_np = flair_warped.numpy()
107
+ mask_np = mask_warped.numpy()
108
+
109
+ combined = t1c_np + t2_np + flair_np
110
+ bbox = get_bbox_from_mask(combined)
111
+
112
+ t1c_c = pad_to_shape(crop_to_bbox(t1c_np, bbox), TARGET_SHAPE)
113
+ t2_c = pad_to_shape(crop_to_bbox(t2_np, bbox), TARGET_SHAPE)
114
+ flair_c = pad_to_shape(crop_to_bbox(flair_np, bbox), TARGET_SHAPE)
115
+ mask_c = pad_to_shape(crop_to_bbox(mask_np, bbox), TARGET_SHAPE)
116
+ mask_c = (mask_c > 0).astype(np.uint8)
117
+
118
+ out_folder = os.path.join(OUT_ROOT, sid)
119
+ os.makedirs(out_folder, exist_ok=True)
120
+ affine = np.eye(4) # spatial correspondence no longer meaningful post-crop/pad; identity is fine for a CNN pipeline
121
+ nib.Nifti1Image(t1c_c.astype(np.float32), affine).to_filename(os.path.join(out_folder, "T1C.nii.gz"))
122
+ nib.Nifti1Image(t2_c.astype(np.float32), affine).to_filename(os.path.join(out_folder, "T2.nii.gz"))
123
+ nib.Nifti1Image(flair_c.astype(np.float32), affine).to_filename(os.path.join(out_folder, "FLAIR.nii.gz"))
124
+ nib.Nifti1Image(mask_c, affine).to_filename(os.path.join(out_folder, "mask.nii.gz"))
125
+ print(f" [done] {sid} final shape={t1c_c.shape}")
126
+
127
+
128
+ if __name__ == "__main__":
129
+ import warnings
130
+ warnings.filterwarnings("ignore")
131
+
132
+ atlas = ants.image_read(ATLAS_PATH)
133
+
134
+ subject_folders = sorted(glob.glob(os.path.join(RAW_ROOT, "UCSF-PDGM-*_nifti")))
135
+ sids = [os.path.basename(f).replace("_nifti", "") for f in subject_folders]
136
+
137
+ if LIMIT is not None:
138
+ sids = sids[:LIMIT]
139
+
140
+ print(f"Processing {len(sids)} subjects...")
141
+ for i, sid in enumerate(sids):
142
+ print(f"[{i+1}/{len(sids)}] {sid}")
143
+ try:
144
+ register_subject(sid, atlas)
145
+ except Exception as e:
146
+ print(f" [ERROR] {sid}: {e}")
code/test_loaders.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys.path.append('.')
3
+ from dataLoder.loader_S2 import get_fold_data, split_path_by_label
4
+
5
+ pkl_paths = ['./1p19q.pkl', './IDH.pkl', './LHG.pkl']
6
+ for p in pkl_paths:
7
+ for fold in range(5):
8
+ file_paths, file_labels = get_fold_data(fold, 'train', p)
9
+ p0, p1 = split_path_by_label(file_paths, file_labels)
10
+ print(f"{p} fold {fold}: len(p0)={len(p0)}, len(p1)={len(p1)}")
code/test_loaders_s1.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys.path.append('.')
3
+ from dataLoder.loader_S1 import get_fold_data, split_path_by_label
4
+
5
+ pkl_paths = ['./1p19q.pkl', './IDH.pkl', './LHG.pkl']
6
+ for p in pkl_paths:
7
+ for fold in range(5):
8
+ file_paths, file_labels = get_fold_data(fold, 'train', p)
9
+ p0, p1 = split_path_by_label(file_paths, file_labels)
10
+ print(f"{p} fold {fold}: len(p0)={len(p0)}, len(p1)={len(p1)}")
code/testgpu.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # test_gpu.py
2
+ import torch
3
+ print(f"PyTorch version: {torch.__version__}")
4
+ print(f"CUDA available: {torch.cuda.is_available()}")
5
+ if torch.cuda.is_available():
6
+ print(f"GPU: {torch.cuda.get_device_name(0)}")
7
+ print(f"GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.2f} GB")
8
+ x = torch.randn(3, 3, 160, 192, 160).cuda()
9
+ print(f"Tensor on GPU: {x.device}")
10
+ del x
11
+ torch.cuda.empty_cache()
12
+ print("✅ CUDA is working!")
13
+ else:
14
+ print("❌ CUDA is NOT available")