File size: 5,334 Bytes
9ee6a3d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Calculate muscle fat percentages from CT images using model predictions
"""

import os
import re
from pathlib import Path
import numpy as np # type: ignore
import pandas as pd # type: ignore
import nibabel as nib # type: ignore

root_100_120 = Path("../100-120")
output_csv_100_120 = Path("../fatty_data/model_pred_dev.csv")

fat_hu_thresh = -20

muscle_labels = {
    1: "psoas",
    2: "quadratus_lumborum",
    3: "paraspinal",
    4: "latissimus_dorsi",
    5: "iliacus",
    6: "rectus_femoris",
    7: "vastus",
    8: "rhomboid",
    9: "trapezius",
}

def load_image_and_label_100_120(case_id: int, root_dir: Path):
    """Load CT image and model prediction label file for cases 100-120."""

    img_path = root_dir / "images_100-120" / f"{case_id}_0000.nii.gz"
    if not img_path.exists():
        return None, None

    lab_path = root_dir / "label_9_muscles_model_pred" / f"{case_id}.nii.gz"
    if not lab_path.exists():
        return None, None
    
    try:
        img = nib.load(str(img_path))  # type: ignore
        lab = nib.load(str(lab_path))  # type: ignore
        return img.get_fdata(), lab.get_fdata()
    except Exception as e:
        print(f"Error loading case {case_id}: {e}")
        return None, None

def calculate_fat_percentages(img_arr: np.ndarray, lab_arr: np.ndarray):
    """Calculate fat percentage (HU <= -20) for all 9 muscle labels."""
    fat_mask = img_arr <= fat_hu_thresh
    fat_percentages = {}
    
    for label_id, muscle_name in muscle_labels.items():
        muscle_mask = (lab_arr == label_id)
        total_voxels = int(np.count_nonzero(muscle_mask))  # type: ignore
        
        if total_voxels == 0:
            fat_pct = 0.0
        else:
            fat_voxels = int(np.count_nonzero(fat_mask & muscle_mask))  # type: ignore
            fat_pct = (fat_voxels / total_voxels) * 100.0
        
        fat_percentages[f"{muscle_name}_fat_pct"] = round(fat_pct, 2)
    
    return fat_percentages

def save_mean_std_stats(df, fat_cols, output_path):
    """Save mean ± SD statistics to a separate CSV file."""
    stats_data = []
    
    for col in fat_cols:
        values = df[col].values
        mean_val = np.mean(values)  # type: ignore
        std_val = np.std(values)  # type: ignore
        
        stats_data.append({
            'muscle': col.replace('_fat_pct', ''),
            'mean': round(mean_val, 2),
            'std': round(std_val, 2),
            'mean_std': f"{mean_val:.2f} ± {std_val:.2f}"
        })
    
    stats_df = pd.DataFrame(stats_data)
    stats_df.to_csv(output_path, index=False)
    print(f"Mean ± SD statistics saved to: {output_path}")

def process_100_120_dataset():
    """Process cases 100-120 using model predictions and save to model_pred_dev.csv"""
    print("="*60)
    print("PROCESSING CASES 100-120 WITH MODEL PREDICTIONS")
    print("="*60)
    
    rows = []

    print("Processing cases 100-120 with model predictions...")
    for case_id in range(100, 121):
        img_arr, lab_arr = load_image_and_label_100_120(case_id, root_100_120)
        if img_arr is not None and lab_arr is not None:
            fat_percentages = calculate_fat_percentages(img_arr, lab_arr)
            record = {"case_id": case_id, "dataset": "100-120_model_pred"}
            record.update(fat_percentages)
            rows.append(record)
            print(f"Case {case_id}: {[v for v in fat_percentages.values()][:3]}... %")
        else:
            print(f"Case {case_id}: Failed to load")
    
    if rows:
        df = pd.DataFrame(rows)

        fat_cols = [col for col in df.columns if col.endswith("_fat_pct")]

        fat_means = df[fat_cols].mean().round(2)
        fat_stds = df[fat_cols].std().round(2)

        summary_row = {"case_id": "Mean ± SD"}
        for col in fat_cols:
            summary_row[col] = f"{fat_means[col]:.2f} ± {fat_stds[col]:.2f}"

        summary_df = pd.DataFrame([summary_row])
        df_with_summary = pd.concat([df, summary_df], ignore_index=True)  # type: ignore

        output_csv_100_120.parent.mkdir(parents=True, exist_ok=True)

        df_with_summary.to_csv(output_csv_100_120, index=False)
        print(f"\nSaved {len(rows)} cases to {output_csv_100_120}")

        print(f"\nFat Percentage Summary (100-120 Model Predictions):")
        for col in fat_cols:
            values = df[col].values
            mean_val = np.mean(values)  # type: ignore
            std_val = np.std(values)  # type: ignore
            print(f"{col}: {mean_val:.2f} ± {std_val:.2f} %")

        save_mean_std_stats(df, fat_cols, output_csv_100_120.parent / "model_pred_dev_mean_std.csv")
    else:
        print("No data processed for 100-120!")

def main():
    """Main function to process the development dataset with model predictions."""
    print("FATTY PERCENTAGE ANALYSIS - MODEL PREDICTIONS")
    print("Computing fat percentage (HU <= -20) for 9 muscle labels using model predictions")
    print("="*60)

    process_100_120_dataset()
    
    print("\n" + "="*60)
    print("ANALYSIS COMPLETE")
    print("="*60)
    print(f"Results saved to:")
    print(f"  - {output_csv_100_120} (cases 100-120 with model predictions)")
    print(f"  - {output_csv_100_120.parent / 'model_pred_dev_mean_std.csv'} (summary statistics)")

if __name__ == "__main__":
    main()