File size: 9,078 Bytes
4e279f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ee6a3d
4e279f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Calculate muscle fat percentages from CT images
"""

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")
label_root_251_500 = Path("../model_training/251-500_out")
image_root_251_500 = Path("../model_training/251-500_in")

output_csv_100_120 = Path("../fatty_data/dev_fat.csv")
output_csv_251_500 = Path("../fatty_data/test_fat.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 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 / "labels_9_muscles" / 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 load_image_and_label_251_500(case_id: int):
    """Load CT image and label file for cases 251-500."""

    img_path = image_root_251_500 / f"AtlasDataset_{case_id:06d}_0000.nii.gz"
    if not img_path.exists():
        print(f"Image not found: {img_path}")
        return None, None

    lab_path = label_root_251_500 / f"AtlasDataset_{case_id:06d}.nii.gz"
    if not lab_path.exists():
        print(f"Label not found: {lab_path}")
        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 extract_case_ids_from_labels():
    """Extract case IDs from label folder files (251-500)."""
    case_ids = []
    if not label_root_251_500.exists():
        print(f"Label folder not found: {label_root_251_500}")
        return case_ids

    pattern = re.compile(r'AtlasDataset_(\d+)\.nii\.gz')
    
    for file_path in label_root_251_500.glob("*.nii.gz"):
        match = pattern.match(file_path.name)
        if match:
            case_id = int(match.group(1))
            case_ids.append(case_id)
    
    return sorted(case_ids)

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 and save to fatty_atrophy.csv"""
    print("="*60)
    print("PROCESSING CASES 100-120")
    print("="*60)
    
    rows = []

    print("Processing cases 100-120...")
    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"}
            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):")
        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 / "dev_fat_mean_std.csv")
    else:
        print("No data processed for 100-120!")

def process_251_500_dataset():
    """Process cases 251-500 and save to test_fat.csv"""
    print("\n" + "="*60)
    print("PROCESSING CASES 251-500")
    print("="*60)
    
    print("Extracting case IDs from label folder...")
    case_ids = extract_case_ids_from_labels()
    
    if not case_ids:
        print("No case IDs found in label folder!")
        return
    
    print(f"Found {len(case_ids)} cases in label folder: {case_ids[:5]}...{case_ids[-5:]}")
    
    rows = []
    processed_count = 0
    failed_count = 0
    
    print(f"\nProcessing {len(case_ids)} cases...")
    for i, case_id in enumerate(case_ids, 1):
        print(f"Processing case {case_id} ({i}/{len(case_ids)})...")
        
        img_arr, lab_arr = load_image_and_label_251_500(case_id)
        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": "251-500"}
            record.update(fat_percentages)
            rows.append(record)
            processed_count += 1

            sample_values = [v for v in fat_percentages.values()][:3]
            print(f"  Case {case_id}: {sample_values}... %")
        else:
            failed_count += 1
            print(f"  Case {case_id}: Failed to load")
    
    print(f"\nProcessing complete: {processed_count} successful, {failed_count} failed")
    
    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_251_500.parent.mkdir(parents=True, exist_ok=True)

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

        print(f"\nFat Percentage Summary (251-500):")
        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_251_500.parent / "test_fat_mean_std.csv")
    else:
        print("No data processed for 251-500!")

def main():
    """Main function to process both datasets."""
    print("FATTY PERCENTAGE ANALYSIS")
    print("Computing fat percentage (HU <= -20) for 9 muscle labels")
    print("="*60)

    process_100_120_dataset()

    process_251_500_dataset()
    
    print("\n" + "="*60)
    print("ANALYSIS COMPLETE")
    print("="*60)
    print(f"Results saved to:")
    print(f"  - {output_csv_100_120} (cases 100-120)")
    print(f"  - {output_csv_251_500} (cases 251-500)")

if __name__ == "__main__":
    main()