File size: 35,121 Bytes
012148b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
import os
import glob
import pandas as pd
from PIL import Image
import torch
from torch.utils.data import Dataset, DataLoader, random_split
import torchvision.transforms as T
import torch.nn as nn
import torch.optim as optim
from tqdm import tqdm
import timm
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
import matplotlib.pyplot as plt
import cv2

#############################################
# Helper Functions for Visualization
#############################################
def plot_bland_altman(preds, targets, filename="bland_altman.png"):
    avg = (preds + targets) / 2.0
    diff = preds - targets
    md = np.mean(diff)
    sd = np.std(diff)
    loa_upper = md + 1.96 * sd
    loa_lower = md - 1.96 * sd

    plt.figure(figsize=(8,6))
    plt.scatter(avg, diff, alpha=0.6)
    plt.axhline(0, color='black', linestyle='-')
    plt.axhline(md, color='red', linestyle='-', label=f"Mean Diff = {md:.2f}")
    plt.axhline(loa_upper, color='red', linestyle='--', label=f"+1.96 SD = {loa_upper:.2f}")
    plt.axhline(loa_lower, color='red', linestyle='--', label=f"-1.96 SD = {loa_lower:.2f}")
    plt.xlabel("Average of Predictions and Ground Truth")
    plt.ylabel("Difference (Predictions - Ground Truth)")
    plt.xlim(0, 100)
    plt.ylim(-40, 40)
    plt.title("Bland–Altman Plot")
    plt.legend()
    plt.savefig(filename)
    plt.close()

def upsample_attention_map(rollout, image_size, patch_size):
    patch_attention = np.mean(rollout, axis=1)  # (N,)
    grid_size = int(np.sqrt(rollout.shape[0]))   # assuming square grid
    patch_attention_map = patch_attention.reshape(grid_size, grid_size)
    patch_attention_tensor = torch.tensor(patch_attention_map).unsqueeze(0).unsqueeze(0).float()
    upsampled = torch.nn.functional.interpolate(patch_attention_tensor, size=image_size, mode='bilinear', align_corners=False)
    return upsampled.squeeze().numpy()

def get_attention_rollout(model, input_tensor, discard_ratio=0.9, image_size=(504,504), patch_size=14):
    if hasattr(model, "blocks"):
        blocks = model.blocks
    elif hasattr(model, "dino") and hasattr(model.dino, "blocks"):
        blocks = model.dino.blocks
    else:
        raise AttributeError("The provided model does not have 'blocks' or 'dino.blocks'.")
    attentions = []
    def hook_fn(module, inp, output):
        attn = output[0] if isinstance(output, (tuple, list)) else output
        attentions.append(attn.detach())
    hooks = []
    for blk in blocks:
        hook = blk.attn.register_forward_hook(hook_fn)
        hooks.append(hook)
    _ = model(input_tensor)
    for hook in hooks:
        hook.remove()
    rollout = torch.eye(attentions[0].shape[-1]).unsqueeze(0).to(attentions[0].device)
    for attn in attentions:
        attn_avg = attn.mean(dim=1)
        flat = attn_avg.view(attn_avg.size(0), -1)
        kth_val, _ = torch.kthvalue(flat, int(flat.size(1)*discard_ratio), dim=1)
        threshold = kth_val.unsqueeze(-1).unsqueeze(-1)
        attn_avg = torch.where(attn_avg < threshold, torch.zeros_like(attn_avg), attn_avg)
        attn_aug = attn_avg + torch.eye(attn_avg.size(-1)).to(attn_avg.device)
        attn_aug = attn_aug / attn_aug.sum(dim=-1, keepdim=True)
        rollout = torch.bmm(rollout, attn_aug)
    rollout = rollout[0].cpu().numpy()
    upsampled_rollout = upsample_attention_map(rollout, image_size, patch_size)
    return upsampled_rollout

def save_attention_map(attn_map, filename="attention_map.png"):
    plt.figure(figsize=(6,6))
    plt.imshow(attn_map, cmap='viridis')
    plt.colorbar()
    plt.title("Attention Rollout")
    plt.savefig(filename)
    plt.close()

def overlay_attention_on_image(chest_img, attn_map, alpha=0.5):
    if isinstance(chest_img, torch.Tensor):
        chest_img = chest_img.cpu().numpy()
    chest_img = np.transpose(chest_img, (1,2,0))
    chest_img = np.clip(chest_img, 0, 1)
    heatmap = cv2.applyColorMap((attn_map*255).astype(np.uint8), cv2.COLORMAP_JET)
    heatmap = cv2.cvtColor(heatmap, cv2.COLOR_BGR2RGB) / 255.0
    overlayed = (1 - alpha) * chest_img + alpha * heatmap
    overlayed = np.clip(overlayed, 0, 1)
    return overlayed

def save_overlay_attention(chest_img, attn_map, filename="overlay_attention.png", alpha=0.5):
    overlayed = overlay_attention_on_image(chest_img, attn_map, alpha=alpha)
    plt.figure(figsize=(8,8))
    plt.imshow(overlayed)
    plt.axis("off")
    plt.title("Attention Overlay")
    plt.savefig(filename, bbox_inches="tight")
    plt.close()

#############################################
# Dataset: CrossValidationDataset with Extra Clinical Variables and Normalization
#############################################
class CrossValidationDataset(Dataset):
    def __init__(self, base_folder, csv_file, chest_transform=None, ecg_transform=None, preload=False):
        self.base_folder = base_folder
        self.chest_transform = chest_transform
        self.ecg_transform = ecg_transform if ecg_transform is not None else T.Compose([
            T.Resize((224,48)),
            T.ToTensor(),
        ])
        self.preload = preload

        self.patient_folders = sorted([os.path.join(base_folder, d)
                                       for d in os.listdir(base_folder)
                                       if os.path.isdir(os.path.join(base_folder, d))])
        df = pd.read_excel(csv_file)
        extra_cols = ["Sex","Age", "HT", "DM", "HL", "smoking", "OMI", "CABG", "Cr", "eGFR", "ROOM_HR", "ROOM_SaO2", "ROOM_SvO2", "ROOM_Hb", "ROOM_O2_Consumption"]
        self.target_mapping = {}
        self.extra_mapping = {}
        df["Sex"] = df["Sex"].apply(lambda x: 0 if x=="F" else (1 if x=="M" else -1))
        df["Age"] = df["Age"].apply(lambda x: x / 100.0 if x >= 0 else -1.0)
        # Compute normalization parameters for mPAP.
        self.mpap_mean = df["ROOM_MPA_m"].mean()
        self.mpap_std = df["ROOM_MPA_m"].std()
        
        for _, row in df.iterrows():
            no = str(int(row['No'])).strip()
            self.target_mapping[no] = row['ROOM_MPA_m']*0.01
            self.extra_mapping[no] = row[extra_cols].values.astype(np.float32)
        
        print (f"Data loading Start: {base_folder}")
        if self.preload:
            print ("Data preload on")
            self.preloaded_data = []
            for patient_folder in tqdm(self.patient_folders, desc=f"Data preloading"):
                no = os.path.basename(patient_folder)
                try:
                    chest_path = os.path.join(patient_folder, f"ChestXray_{no}.png")
                    chest_img = Image.open(chest_path).convert("RGB")
                    if self.chest_transform:
                        chest_img = self.chest_transform(chest_img)
                    else:
                        chest_img = T.ToTensor()(chest_img)
                    
                    ecg_pattern = os.path.join(patient_folder, f"ECG_{no}_LEAD_*.png")
                    ecg_files = sorted(glob.glob(ecg_pattern))
                    if len(ecg_files) < 12:
                        raise ValueError(f"Expected at least 12 ECG images for patient {no}, found {len(ecg_files)}")
                    elif len(ecg_files) > 12:
                        print(f"Warning: Found {len(ecg_files)} ECG images for patient {no}. Using first 12.")
                        ecg_files = ecg_files[:12]
                    ecg_imgs = []
                    for ecg_file in ecg_files:
                        ecg_img = Image.open(ecg_file).convert("RGB")
                        ecg_img = self.ecg_transform(ecg_img)
                        ecg_imgs.append(ecg_img)
                    ecg_tensor = torch.cat(ecg_imgs, dim=0)
                    
                    target = torch.tensor([self.target_mapping[no]], dtype=torch.float32)
         
                    
                    if no not in self.extra_mapping:
                        raise ValueError(f"Extra features for patient {no} not found in {csv_file}.")
                    extra = torch.tensor(self.extra_mapping[no], dtype=torch.float32)
                    
                    self.preloaded_data.append((chest_img, ecg_tensor, target, extra, no))
                except Exception as e:
                    print(f"Skipping patient {no} during preload due to error: {e}")
            print(f"Preloaded {len(self.preloaded_data)} patients into RAM.")
        else:
            print ("Data no-preload")
            self.preloaded_data = None

    def __len__(self):
        return len(self.preloaded_data) if self.preload else len(self.patient_folders)
    
    def __getitem__(self, index):
        if self.preload:
            return self.preloaded_data[index]
        patient_folder = self.patient_folders[index]
        no = os.path.basename(patient_folder)
        chest_path = os.path.join(patient_folder, f"ChestXray_{no}.png")
        chest_img = Image.open(chest_path).convert("RGB")
        if self.chest_transform:
            chest_img = self.chest_transform(chest_img)
        else:
            chest_img = T.ToTensor()(chest_img)
        
        ecg_pattern = os.path.join(patient_folder, f"ECG_{no}_LEAD_*.png")
        ecg_files = sorted(glob.glob(ecg_pattern))
        if len(ecg_files) < 12:
            raise ValueError(f"Expected at least 12 ECG images for patient {no}, found {len(ecg_files)}")
        elif len(ecg_files) > 12:
            print(f"Warning: Found {len(ecg_files)} ECG images for patient {no}. Using first 12.")
            ecg_files = ecg_files[:12]
        ecg_imgs = []
        for ecg_file in ecg_files:
            ecg_img = Image.open(ecg_file).convert("RGB")
            ecg_img = self.ecg_transform(ecg_img)
            ecg_imgs.append(ecg_img)
        ecg_tensor = torch.cat(ecg_imgs, dim=0)
        
        raw_target = torch.tensor([self.target_mapping[no]], dtype=torch.float32)
        target = raw_target
        if no not in self.extra_mapping:
            raise ValueError(f"Extra features for patient {no} not found in {csv_file}.")
        extra = torch.tensor(self.extra_mapping[no], dtype=torch.float32)
        return chest_img, ecg_tensor, target, extra, no

#############################################
# Flexible Multi-modal Regression Model
# Training: 224×224 chest patches.
# Validation/Testing: 512×512 chest images split into 3×3 patches and averaged.
#############################################
class FlexibleMultiModalRegressor(nn.Module):
    def __init__(self,
                 use_chest=True,
                 backbone_type="dino",
                 chest_backbone=None,
                 chest_backbone_name=None,
                 chest_pretrained=True,
                 use_ecg=True,
                 ecg_in_channels=36,
                 use_extra=False,
                 extra_in_dim=15,
                 extra_proj_dim=32):
        super(FlexibleMultiModalRegressor, self).__init__()
        self.use_chest = use_chest
        self.use_ecg = use_ecg
        self.use_extra = use_extra

        # Chest branch: load backbone and freeze its weights.
        if self.use_chest:
            if chest_backbone is not None:
                self.chest_model = chest_backbone
                if hasattr(chest_backbone, "embed_dim"):
                    chest_embed_dim = chest_backbone.embed_dim
                else:
                    chest_embed_dim = chest_backbone.get_classifier().in_features
                    chest_backbone.reset_classifier(0)
                    chest_backbone.embed_dim = chest_embed_dim
            else:
                if backbone_type.lower() == "dino":
                    dino = torch.hub.load('facebookresearch/dinov2', 'dinov2_vits14_reg')
                    self.chest_model = dino
                    chest_embed_dim = getattr(dino, "embed_dim", 1024)
                elif backbone_type.lower() in ["resnet", "vgg"]:
                    if chest_backbone_name is None:
                        chest_backbone_name = "resnet50" if backbone_type.lower() == "resnet" else "vgg16"
                    self.chest_model = timm.create_model(chest_backbone_name, pretrained=chest_pretrained)
                    if hasattr(self.chest_model, "embed_dim"):
                        chest_embed_dim = self.chest_model.embed_dim
                    else:
                        chest_embed_dim = self.chest_model.get_classifier().in_features
                        self.chest_model.reset_classifier(0)
                        self.chest_model.embed_dim = chest_embed_dim
                else:
                    raise ValueError("Invalid backbone_type. Choose 'dino', 'resnet', or 'vgg'.")
            for param in self.chest_model.parameters():
                param.requires_grad = False
            self.chest_embed_dim = chest_embed_dim

        # ECG branch.
        if self.use_ecg:
            self.ecg_branch = nn.Sequential(
                nn.Conv2d(ecg_in_channels, 64, kernel_size=3, stride=1, padding=1),
                nn.BatchNorm2d(64),
                nn.ReLU(inplace=True),
                nn.MaxPool2d(2),
                nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
                nn.BatchNorm2d(128),
                nn.ReLU(inplace=True),
                nn.MaxPool2d(2),
                nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
                nn.BatchNorm2d(256),
                nn.ReLU(inplace=True),
                nn.MaxPool2d(2)
            )
            self.ecg_pool = nn.AdaptiveAvgPool2d((1, 1))
            self.ecg_fc = nn.Linear(256, 128)
            self.ecg_dim = 128
            if not self.use_chest:
                self.ecg_regressor = nn.Sequential(
                    nn.Linear(self.ecg_dim, self.ecg_dim // 2),
                    nn.ReLU(inplace=True),
                    nn.Linear(self.ecg_dim // 2, 1)
                )
        # Extra branch.
        if self.use_extra:
            self.extra_fc = nn.Sequential(
                nn.Linear(extra_in_dim, extra_proj_dim),
                nn.ReLU(inplace=True)
            )
            self.extra_dim = extra_proj_dim

        # Patch regressor for the chest branch.
        if self.use_chest and self.use_ecg:
            in_dim = self.chest_embed_dim + self.ecg_dim
        elif self.use_chest:
            in_dim = self.chest_embed_dim
        if self.use_chest:
            self.patch_regressor = nn.Sequential(
                nn.Linear(in_dim, in_dim // 2),
                nn.ReLU(inplace=True),
                nn.Linear(in_dim // 2, 1)
            )

        # Final fusion with extra features.
        if self.use_extra:
            self.final_regressor = nn.Sequential(
                nn.Linear(1 + self.extra_dim, (1 + self.extra_dim) // 2),
                nn.ReLU(inplace=True),
                nn.Linear((1 + self.extra_dim) // 2, 1)
            )
        else:
            self.final_regressor = None

    def forward(self, chest=None, ecg=None, extra=None):
        # Process ECG modality.
        if self.use_ecg:
            if ecg is None:
                raise ValueError("ECG input must be provided.")
            ecg_feat = self.ecg_branch(ecg)
            ecg_feat = self.ecg_pool(ecg_feat)
            ecg_feat = self.ecg_fc(ecg_feat.view(ecg_feat.size(0), -1))
        else:
            ecg_feat = None

        # Process chest modality if enabled.
        if self.use_chest:
            if chest is None:
                raise ValueError("Chest input must be provided.")
            # Training: chest input is 224x224.
            if chest.shape[-2] == 224 and chest.shape[-1] == 224:
                chest_feat = self.chest_model(chest)
                combined = torch.cat([chest_feat, ecg_feat], dim=1) if ecg_feat is not None else chest_feat
                patch_pred = self.patch_regressor(combined)
                avg_patch_pred = patch_pred
            else:
                # Validation/Testing: chest input is 512x512.
                B, C, H, W = chest.shape
                patch_size = 224
                num_patches_h, num_patches_w = 3, 3
                stride_h = (H - patch_size) // (num_patches_h - 1) if num_patches_h > 1 else patch_size
                stride_w = (W - patch_size) // (num_patches_w - 1) if num_patches_w > 1 else patch_size
                patches = chest.unfold(2, patch_size, stride_h).unfold(3, patch_size, stride_w)
                patches = patches.contiguous().view(B, C, -1, patch_size, patch_size)
                patches = patches.permute(0, 2, 1, 3, 4)  # (B, L, C, patch_size, patch_size)
                B, L, C, ph, pw = patches.shape
                patches = patches.reshape(B * L, C, ph, pw)
                chest_feats = self.chest_model(patches)
                chest_feats = chest_feats.view(B, L, -1)
                if ecg_feat is not None:
                    ecg_feats = ecg_feat.unsqueeze(1).repeat(1, L, 1)
                    combined_feats = torch.cat([chest_feats, ecg_feats], dim=2)
                else:
                    combined_feats = chest_feats
                combined_feats = combined_feats.view(B * L, -1)
                patch_preds = self.patch_regressor(combined_feats)
                patch_preds = patch_preds.view(B, L)
                avg_patch_pred = patch_preds.mean(dim=1, keepdim=True)
            final_pred = avg_patch_pred
        else:
            final_pred = self.ecg_regressor(ecg_feat)

        if self.use_extra:
            if extra is None:
                raise ValueError("Extra features must be provided.")
            extra_feat = self.extra_fc(extra)
            combined_final = torch.cat([final_pred, extra_feat], dim=1)
            final_pred = self.final_regressor(combined_final)
        return final_pred

#############################################
# Training and Evaluation Loop
#############################################
def train_and_evaluate(outfolder, model, train_loader, val_loader, test_loader, device, num_epochs=10, lr=1e-4,
                       cv_idx=0, backbone_str="model", use_chest=True, use_ecg=True, use_extra=False):
    criterion = nn.MSELoss()
    optimizer = optim.Adam(model.parameters(), lr=lr)
    
    model.to(device)
    
    os.makedirs(f"{outfolder}/best_models/", exist_ok=True)
    best_model_filename = f"{outfolder}/best_models/cv{cv_idx}_{backbone_str}_chest{use_chest}_ECG{use_ecg}_extra{use_extra}.pth"
    best_val_loss = float("inf")
    
    for epoch in range(num_epochs):
        model.train()
        running_loss = 0.0
        for batch in tqdm(train_loader, desc=f"Epoch {epoch+1} Training"):
            if len(batch) == 5:
                chest_imgs, ecg_inputs, targets, extra, _ = batch
            else:
                chest_imgs, ecg_inputs, targets, _ = batch
                extra = None
            chest_imgs = chest_imgs.to(device) if use_chest else None
            ecg_inputs = ecg_inputs.to(device) if use_ecg else None
            targets = targets.to(device)
            extra = extra.to(device) if (use_extra and extra is not None) else None
            
            optimizer.zero_grad()
            outputs = model(chest=chest_imgs, ecg=ecg_inputs, extra=extra)
            loss = criterion(outputs, targets)
            loss.backward()
            optimizer.step()
            batch_size = chest_imgs.size(0) if use_chest else (ecg_inputs.size(0) if use_ecg else targets.size(0))
            running_loss += loss.item() * batch_size
        train_loss = running_loss / len(train_loader.dataset)
        print(f"Epoch {epoch+1} Training Loss: {train_loss:.4f}")
        
        model.eval()
        val_loss = 0.0
        with torch.no_grad():
            for batch in tqdm(val_loader, desc=f"Epoch {epoch+1} Validation"):
                if len(batch) == 5:
                    chest_imgs, ecg_inputs, targets, extra, _ = batch
                else:
                    chest_imgs, ecg_inputs, targets, _ = batch
                    extra = None
                chest_imgs = chest_imgs.to(device) if use_chest else None
                ecg_inputs = ecg_inputs.to(device) if use_ecg else None
                targets = targets.to(device)
                extra = extra.to(device) if (use_extra and extra is not None) else None
                outputs = model(chest=chest_imgs, ecg=ecg_inputs, extra=extra)
                loss = criterion(outputs, targets)
                batch_size = chest_imgs.size(0) if use_chest else (ecg_inputs.size(0) if use_ecg else targets.size(0))
                val_loss += loss.item() * batch_size
        val_loss /= len(val_loader.dataset)
        print(f"Epoch {epoch+1} Validation Loss: {val_loss:.4f}")
        
        if val_loss < best_val_loss:
            best_val_loss = val_loss
            torch.save(model.state_dict(), best_model_filename)
            print("Saved best model as", best_model_filename)
    
    print("Training complete. Best Validation Loss: {:.4f}".format(best_val_loss))
    model.load_state_dict(torch.load(best_model_filename))
    model.eval()
    test_loss = 0.0
    all_preds = []
    all_targets = []
    patient_numbers = []
    with torch.no_grad():
        for batch in tqdm(test_loader, desc="Testing"):
            if len(batch) == 5:
                chest_imgs, ecg_inputs, targets, extra, nos = batch
            else:
                chest_imgs, ecg_inputs, targets, _ = batch
                extra = None
            chest_imgs = chest_imgs.to(device) if use_chest else None
            ecg_inputs = ecg_inputs.to(device) if use_ecg else None
            targets = targets.to(device)
            extra = extra.to(device) if (use_extra and extra is not None) else None
            outputs = model(chest=chest_imgs, ecg=ecg_inputs, extra=extra)
            loss = criterion(outputs, targets)
            batch_size = chest_imgs.size(0) if use_chest else (ecg_inputs.size(0) if use_ecg else targets.size(0))
            test_loss += loss.item() * batch_size
            all_preds.append(outputs.cpu())
            all_targets.append(targets.cpu())
            patient_numbers.extend(nos)
    
    test_loss /= len(test_loader.dataset)
    print("Test Loss: {:.4f}".format(test_loss))

    all_preds = torch.cat(all_preds).numpy().flatten()
    all_targets = torch.cat(all_targets).numpy().flatten()

    # Unnormalize predictions and targets.
    all_preds = all_preds *100.0
    all_targets = all_targets *100.0

    rmse = np.sqrt(mean_squared_error(all_targets, all_preds))
    mae = np.mean(np.abs(all_targets - all_preds))
    r2 = r2_score(all_targets, all_preds)
    print(f"RMSE: {rmse:.4f}")
    print(f"MAE: {mae:.4f}")
    print(f"R^2 Score: {r2:.4f}")
    
    scatterfolder = f"{outfolder}/pred_vs_gt/"
    os.makedirs(scatterfolder, exist_ok=True)
    filename = f"{backbone_str}_chest{use_chest}_ECG{use_ecg}_extra{use_extra}.png"
    scatter_filename = os.path.join(scatterfolder, filename)
    
    plt.figure(figsize=(8,8))
    plt.scatter(all_targets, all_preds, alpha=0.6)
    plt.plot([all_targets.min(), all_targets.max()], [all_targets.min(), all_targets.max()], 'r--')
    plt.xlabel("Ground Truth")
    plt.ylabel("Predictions")
    plt.title("Predictions vs Ground Truth")
    plt.savefig(scatter_filename)
    plt.close()
    
    results_df = pd.DataFrame({
        "PatientNo": patient_numbers,
        "all_targets": all_targets,
        "Prediction": all_preds
    })
    valuesfolder = f"{outfolder}/values/"
    os.makedirs(valuesfolder, exist_ok=True)
    csv_filename = os.path.join(valuesfolder, f"{backbone_str}_chest{use_chest}_ECG{use_ecg}_extra{use_extra}.csv")
    results_df.to_csv(csv_filename, index=False)

    residualsfolder = f"{outfolder}/residual_hist/"
    os.makedirs(residualsfolder, exist_ok=True)
    hist_filename = os.path.join(residualsfolder, filename)
    
    residuals = all_targets - all_preds

    plt.figure(figsize=(8,6))
    plt.hist(residuals, bins=30, alpha=0.7)
    plt.xlabel("Residual")
    plt.ylabel("Frequency")
    plt.title("Residual Distribution")
    plt.savefig(hist_filename)
    plt.close()
    
    blandfolder = f"{outfolder}/bland_altman/"
    os.makedirs(blandfolder, exist_ok=True)
    bland_filename = os.path.join(blandfolder, filename)
    
    plot_bland_altman(all_preds, all_targets, filename=bland_filename)
    
    metrics = {
        "cv_idx": cv_idx,
        "backbone": backbone_str,
        "use_chest": use_chest,
        "use_ecg": use_ecg,
        "use_extra": use_extra,
        "Test Loss": test_loss,
        "RMSE": rmse,
        "MAE": mae,
        "R2": r2,
        "Scatter Plot": scatter_filename,
        "Residual Histogram": hist_filename,
        "Bland-Altman Plot": bland_filename
    }
    return metrics

#############################################
# Main: Setup DataLoaders, Create Models, Run Experiments, and Collect Metrics
#############################################
if __name__ == "__main__":
    import torchvision.transforms as T
    from torch.utils.data import DataLoader, random_split
    # Define transforms.
    chest_transform_train = T.Compose([
        T.Resize((512,512)),
        T.RandomCrop(224),
        T.ToTensor(),
        T.Normalize(mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225])
    ])
    chest_transform_test = T.Compose([
        T.Resize((512,512)),
        T.ToTensor(),
        T.Normalize(mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225])
    ])
    ecg_transform = T.Compose([
        T.Resize((224,48)),
        T.ToTensor(),
        T.Normalize(mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225])
    ])
    
    torch.manual_seed(42)
    
    print("Job Start")
    setting = 1
    cv_idx = 0
    num_epochs = 20
    if setting == 0:
        root = "/Users/sy1045/syhome"
        base_folder_train = f"{root}/2_dataset_secure/Sapporo/Crossvalidation/Cross{cv_idx}/train"
        base_folder_test = f"{root}/2_dataset_secure/Sapporo/Crossvalidation/Cross{cv_idx}/test"
        csv_file = f"{root}/2_dataset_secure/Sapporo/Table_clean.xlsx"
    elif setting == 1:
        root = "/home/local/PARTNERS/sy1045/syhome"
        base_folder_train = f"{root}/2_Datasets/15_Sapporo/Develop/Crossvalidation_re/Cross{cv_idx}/train"
        base_folder_test = f"{root}/2_Datasets/15_Sapporo/Develop/Crossvalidation_re/Cross{cv_idx}/test"
        csv_file = f"{root}/2_Datasets/15_Sapporo/Develop/Table_clean.xlsx"
    else:
        root = "/Volumes/HOMEDIR$/"
        base_folder_train = f"{root}/2_Datasets/15_Sapporo/CleanDevelopment_re/Crossvalidation_re/Cross{cv_idx}/train"
        base_folder_test = f"{root}/2_Datasets/15_Sapporo/CleanDevelopment_re/Crossvalidation_re/Cross{cv_idx}/test"
        csv_file = f"{root}/2_Datasets/15_Sapporo/CleanDevelopment_re/Table_clean.xlsx"
        
    print("data root :", base_folder_train)
    outfolder = f"{root}/0_TrainingOutputs/15_Sapporo/MICCAI2025-CropperVGG-{num_epochs}epochs/"
    os.makedirs(outfolder, exist_ok=True)
    
    print("Out folder Created :", outfolder)
    full_train_dataset = CrossValidationDataset(base_folder_train, csv_file, chest_transform_train, ecg_transform, preload=True)
    train_size = int(0.9 * len(full_train_dataset))
    val_size = len(full_train_dataset) - train_size
    train_subset, val_subset = random_split(full_train_dataset, [train_size, val_size])
    
    full_test_dataset = CrossValidationDataset(base_folder_test, csv_file, chest_transform_test, ecg_transform, preload=False)
    
    print("Dataloading  :", outfolder)
    train_loader = DataLoader(train_subset, batch_size=4, shuffle=True, num_workers=2)
    val_loader = DataLoader(val_subset, batch_size=4, shuffle=True, num_workers=2)
    test_loader = DataLoader(full_test_dataset, batch_size=1, shuffle=False, num_workers=2)
    
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    
    results = []

    for use_ecg in [True]:
        for use_chest in [True]:
            for use_extra in [False]:
                if not (use_chest or use_ecg or use_extra):
                    continue

        
                
                print(f"=== Experiment: use_chest = {use_chest}, use_ecg = {use_ecg}, use_extra = {use_extra} with VGG16 ===")
                model_vgg = FlexibleMultiModalRegressor(use_chest=use_chest,
                                                        backbone_type="vgg",
                                                        chest_backbone_name="vgg16",
                                                        chest_pretrained=True,
                                                        use_ecg=use_ecg,
                                                        use_extra=use_extra)
                metrics_vgg = train_and_evaluate(outfolder, model_vgg, train_loader, val_loader, test_loader, device,
                                                 num_epochs=num_epochs, lr=5e-5, cv_idx=cv_idx,
                                                 backbone_str="vgg16",
                                                 use_chest=use_chest, use_ecg=use_ecg, use_extra=use_extra)
                if metrics_vgg is not None:
                    results.append(metrics_vgg)
                                
                print(f"=== Experiment: use_chest = {use_chest}, use_ecg = {use_ecg}, use_extra = {use_extra} with vgg19 ===")
                model_vgg = FlexibleMultiModalRegressor(use_chest=use_chest,
                                                        backbone_type="vgg",
                                                        chest_backbone_name="vgg19",
                                                        chest_pretrained=True,
                                                        use_ecg=use_ecg,
                                                        use_extra=use_extra)
                metrics_vgg = train_and_evaluate(outfolder, model_vgg, train_loader, val_loader, test_loader, device,
                                                 num_epochs=num_epochs, lr=5e-5, cv_idx=cv_idx,
                                                 backbone_str="vgg19",
                                                 use_chest=use_chest, use_ecg=use_ecg, use_extra=use_extra)
                if metrics_vgg is not None:
                    results.append(metrics_vgg)
    """
    for use_ecg in [False]:
        for use_chest in [True]:
            for use_extra in [False]:
                if not (use_chest or use_ecg or use_extra):
                    continue

                print(f"=== Experiment: use_chest = {use_chest}, use_ecg = {use_ecg}, use_extra = {use_extra} with ResNet34 ===")
                model_resnet = FlexibleMultiModalRegressor(use_chest=use_chest,
                                                        backbone_type="resnet",
                                                        chest_backbone_name="resnet34",
                                                        chest_pretrained=True,
                                                        use_ecg=use_ecg,
                                                        use_extra=use_extra)
                metrics_resnet = train_and_evaluate(outfolder, model_resnet, train_loader, val_loader, test_loader, device,
                                                    num_epochs=num_epochs, lr=5e-5, cv_idx=cv_idx,
                                                    backbone_str="resnet34",
                                                    use_chest=use_chest, use_ecg=use_ecg, use_extra=use_extra)
                if metrics_resnet is not None:
                    results.append(metrics_resnet)
                    
                print(f"=== Experiment: use_chest = {use_chest}, use_ecg = {use_ecg}, use_extra = {use_extra} with resnet50 ===")
                model_resnet = FlexibleMultiModalRegressor(use_chest=use_chest,
                                                        backbone_type="resnet",
                                                        chest_backbone_name="resnet50",
                                                        chest_pretrained=True,
                                                        use_ecg=use_ecg,
                                                        use_extra=use_extra)
                metrics_resnet = train_and_evaluate(outfolder, model_resnet, train_loader, val_loader, test_loader, device,
                                                    num_epochs=num_epochs, lr=5e-5, cv_idx=cv_idx,
                                                    backbone_str="resnet50",
                                                    use_chest=use_chest, use_ecg=use_ecg, use_extra=use_extra)
                if metrics_resnet is not None:
                    results.append(metrics_resnet)

                
                print(f"=== Experiment: use_chest = {use_chest}, use_ecg = {use_ecg}, use_extra = {use_extra} with VGG16 ===")
                model_vgg = FlexibleMultiModalRegressor(use_chest=use_chest,
                                                        backbone_type="vgg",
                                                        chest_backbone_name="vgg16",
                                                        chest_pretrained=True,
                                                        use_ecg=use_ecg,
                                                        use_extra=use_extra)
                metrics_vgg = train_and_evaluate(outfolder, model_vgg, train_loader, val_loader, test_loader, device,
                                                 num_epochs=num_epochs, lr=5e-5, cv_idx=cv_idx,
                                                 backbone_str="vgg16",
                                                 use_chest=use_chest, use_ecg=use_ecg, use_extra=use_extra)
                if metrics_vgg is not None:
                    results.append(metrics_vgg)
                                
                print(f"=== Experiment: use_chest = {use_chest}, use_ecg = {use_ecg}, use_extra = {use_extra} with vgg19 ===")
                model_vgg = FlexibleMultiModalRegressor(use_chest=use_chest,
                                                        backbone_type="vgg",
                                                        chest_backbone_name="vgg19",
                                                        chest_pretrained=True,
                                                        use_ecg=use_ecg,
                                                        use_extra=use_extra)
                metrics_vgg = train_and_evaluate(outfolder, model_vgg, train_loader, val_loader, test_loader, device,
                                                 num_epochs=num_epochs, lr=5e-5, cv_idx=cv_idx,
                                                 backbone_str="vgg19",
                                                 use_chest=use_chest, use_ecg=use_ecg, use_extra=use_extra)
                if metrics_vgg is not None:
                    results.append(metrics_vgg)
    """

    df_results = pd.DataFrame(results)
    print("Summary of Metrics:")
    print(df_results)
    df_results.to_csv(f"{outfolder}/experiment_summary.csv", index=False)