onlineinfoh commited on
Commit
4e279f6
·
1 Parent(s): 1b1be04

fat% correlation analysis

Browse files
Files changed (1) hide show
  1. scripts/fatty_analysis.py +269 -0
scripts/fatty_analysis.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Calculate muscle fat percentages from CT images
4
+ """
5
+
6
+ import os
7
+ import re
8
+ from pathlib import Path
9
+ import numpy as np # type: ignore
10
+ import pandas as pd # type: ignore
11
+ import nibabel as nib # type: ignore
12
+
13
+ root_100_120 = Path("../100-120")
14
+ label_root_251_500 = Path("../model_training/251-500_out")
15
+ image_root_251_500 = Path("../model_training/251-500_in")
16
+
17
+ output_csv_100_120 = Path("../fatty_data/dev_fat.csv")
18
+ output_csv_251_500 = Path("../fatty_data/test_fat.csv")
19
+
20
+ fat_hu_thresh = -20
21
+
22
+ muscle_labels = {
23
+ 1: "psoas",
24
+ 2: "quadratus_lumborum",
25
+ 3: "paraspinal",
26
+ 4: "latissimus_dorsi",
27
+ 5: "iliacus",
28
+ 6: "rectus_femoris",
29
+ 7: "vastus",
30
+ 8: "rhomboid",
31
+ 9: "trapezius",
32
+ }
33
+
34
+ def load_image_and_label_100_120(case_id: int, root_dir: Path):
35
+ """Load CT image and label file for cases 100-120."""
36
+
37
+ img_path = root_dir / "images_100-120" / f"{case_id}_0000.nii.gz"
38
+ if not img_path.exists():
39
+ return None, None
40
+
41
+ lab_path = root_dir / "labels_9_muscles" / f"{case_id}.nii.gz"
42
+ if not lab_path.exists():
43
+ return None, None
44
+
45
+ try:
46
+ img = nib.load(str(img_path)) # type: ignore
47
+ lab = nib.load(str(lab_path)) # type: ignore
48
+ return img.get_fdata(), lab.get_fdata()
49
+ except Exception as e:
50
+ print(f"Error loading case {case_id}: {e}")
51
+ return None, None
52
+
53
+ def load_image_and_label_251_500(case_id: int):
54
+ """Load CT image and label file for cases 251-500."""
55
+
56
+ img_path = image_root_251_500 / f"AtlasDataset_{case_id:06d}_0000.nii.gz"
57
+ if not img_path.exists():
58
+ print(f"Image not found: {img_path}")
59
+ return None, None
60
+
61
+ lab_path = label_root_251_500 / f"AtlasDataset_{case_id:06d}.nii.gz"
62
+ if not lab_path.exists():
63
+ print(f"Label not found: {lab_path}")
64
+ return None, None
65
+
66
+ try:
67
+ img = nib.load(str(img_path)) # type: ignore
68
+ lab = nib.load(str(lab_path)) # type: ignore
69
+ return img.get_fdata(), lab.get_fdata()
70
+ except Exception as e:
71
+ print(f"Error loading case {case_id}: {e}")
72
+ return None, None
73
+
74
+ def extract_case_ids_from_labels():
75
+ """Extract case IDs from label folder files (251-500)."""
76
+ case_ids = []
77
+ if not label_root_251_500.exists():
78
+ print(f"Label folder not found: {label_root_251_500}")
79
+ return case_ids
80
+
81
+ pattern = re.compile(r'AtlasDataset_(\d+)\.nii\.gz')
82
+
83
+ for file_path in label_root_251_500.glob("*.nii.gz"):
84
+ match = pattern.match(file_path.name)
85
+ if match:
86
+ case_id = int(match.group(1))
87
+ case_ids.append(case_id)
88
+
89
+ return sorted(case_ids)
90
+
91
+ def calculate_fat_percentages(img_arr: np.ndarray, lab_arr: np.ndarray):
92
+ """Calculate fat percentage (HU <= -20) for all 9 muscle labels."""
93
+ fat_mask = img_arr <= fat_hu_thresh # boolean, HU <= -20
94
+ fat_percentages = {}
95
+
96
+ for label_id, muscle_name in muscle_labels.items():
97
+ muscle_mask = (lab_arr == label_id)
98
+ total_voxels = int(np.count_nonzero(muscle_mask)) # type: ignore
99
+
100
+ if total_voxels == 0:
101
+ fat_pct = 0.0
102
+ else:
103
+ fat_voxels = int(np.count_nonzero(fat_mask & muscle_mask)) # type: ignore
104
+ fat_pct = (fat_voxels / total_voxels) * 100.0
105
+
106
+ fat_percentages[f"{muscle_name}_fat_pct"] = round(fat_pct, 2)
107
+
108
+ return fat_percentages
109
+
110
+ def save_mean_std_stats(df, fat_cols, output_path):
111
+ """Save mean ± SD statistics to a separate CSV file."""
112
+ stats_data = []
113
+
114
+ for col in fat_cols:
115
+ values = df[col].values
116
+ mean_val = np.mean(values) # type: ignore
117
+ std_val = np.std(values) # type: ignore
118
+
119
+ stats_data.append({
120
+ 'muscle': col.replace('_fat_pct', ''),
121
+ 'mean': round(mean_val, 2),
122
+ 'std': round(std_val, 2),
123
+ 'mean_std': f"{mean_val:.2f} ± {std_val:.2f}"
124
+ })
125
+
126
+ stats_df = pd.DataFrame(stats_data)
127
+ stats_df.to_csv(output_path, index=False)
128
+ print(f"Mean ± SD statistics saved to: {output_path}")
129
+
130
+ def process_100_120_dataset():
131
+ """Process cases 100-120 and save to fatty_atrophy.csv"""
132
+ print("="*60)
133
+ print("PROCESSING CASES 100-120")
134
+ print("="*60)
135
+
136
+ rows = []
137
+
138
+ print("Processing cases 100-120...")
139
+ for case_id in range(100, 121):
140
+ img_arr, lab_arr = load_image_and_label_100_120(case_id, root_100_120)
141
+ if img_arr is not None and lab_arr is not None:
142
+ fat_percentages = calculate_fat_percentages(img_arr, lab_arr)
143
+ record = {"case_id": case_id, "dataset": "100-120"}
144
+ record.update(fat_percentages)
145
+ rows.append(record)
146
+ print(f"Case {case_id}: {[v for v in fat_percentages.values()][:3]}... %")
147
+ else:
148
+ print(f"Case {case_id}: Failed to load")
149
+
150
+ if rows:
151
+ df = pd.DataFrame(rows)
152
+
153
+ fat_cols = [col for col in df.columns if col.endswith("_fat_pct")]
154
+
155
+ fat_means = df[fat_cols].mean().round(2)
156
+ fat_stds = df[fat_cols].std().round(2)
157
+
158
+ summary_row = {"case_id": "Mean ± SD"}
159
+ for col in fat_cols:
160
+ summary_row[col] = f"{fat_means[col]:.2f} ± {fat_stds[col]:.2f}"
161
+
162
+ summary_df = pd.DataFrame([summary_row])
163
+ df_with_summary = pd.concat([df, summary_df], ignore_index=True) # type: ignore
164
+
165
+ output_csv_100_120.parent.mkdir(parents=True, exist_ok=True)
166
+
167
+ df_with_summary.to_csv(output_csv_100_120, index=False)
168
+ print(f"\nSaved {len(rows)} cases to {output_csv_100_120}")
169
+
170
+ print(f"\nFat Percentage Summary (100-120):")
171
+ for col in fat_cols:
172
+ values = df[col].values
173
+ mean_val = np.mean(values) # type: ignore
174
+ std_val = np.std(values) # type: ignore
175
+ print(f"{col}: {mean_val:.2f} ± {std_val:.2f} %")
176
+
177
+ save_mean_std_stats(df, fat_cols, output_csv_100_120.parent / "dev_fat_mean_std.csv")
178
+ else:
179
+ print("No data processed for 100-120!")
180
+
181
+ def process_251_500_dataset():
182
+ """Process cases 251-500 and save to test_fat.csv"""
183
+ print("\n" + "="*60)
184
+ print("PROCESSING CASES 251-500")
185
+ print("="*60)
186
+
187
+ print("Extracting case IDs from label folder...")
188
+ case_ids = extract_case_ids_from_labels()
189
+
190
+ if not case_ids:
191
+ print("No case IDs found in label folder!")
192
+ return
193
+
194
+ print(f"Found {len(case_ids)} cases in label folder: {case_ids[:5]}...{case_ids[-5:]}")
195
+
196
+ rows = []
197
+ processed_count = 0
198
+ failed_count = 0
199
+
200
+ print(f"\nProcessing {len(case_ids)} cases...")
201
+ for i, case_id in enumerate(case_ids, 1):
202
+ print(f"Processing case {case_id} ({i}/{len(case_ids)})...")
203
+
204
+ img_arr, lab_arr = load_image_and_label_251_500(case_id)
205
+ if img_arr is not None and lab_arr is not None:
206
+ fat_percentages = calculate_fat_percentages(img_arr, lab_arr)
207
+ record = {"case_id": case_id, "dataset": "251-500"}
208
+ record.update(fat_percentages)
209
+ rows.append(record)
210
+ processed_count += 1
211
+
212
+ sample_values = [v for v in fat_percentages.values()][:3]
213
+ print(f" Case {case_id}: {sample_values}... %")
214
+ else:
215
+ failed_count += 1
216
+ print(f" Case {case_id}: Failed to load")
217
+
218
+ print(f"\nProcessing complete: {processed_count} successful, {failed_count} failed")
219
+
220
+ if rows:
221
+ df = pd.DataFrame(rows)
222
+
223
+ fat_cols = [col for col in df.columns if col.endswith("_fat_pct")]
224
+
225
+ fat_means = df[fat_cols].mean().round(2)
226
+ fat_stds = df[fat_cols].std().round(2)
227
+
228
+ summary_row = {"case_id": "Mean ± SD"}
229
+ for col in fat_cols:
230
+ summary_row[col] = f"{fat_means[col]:.2f} ± {fat_stds[col]:.2f}"
231
+
232
+ summary_df = pd.DataFrame([summary_row])
233
+ df_with_summary = pd.concat([df, summary_df], ignore_index=True) # type: ignore
234
+
235
+ output_csv_251_500.parent.mkdir(parents=True, exist_ok=True)
236
+
237
+ df_with_summary.to_csv(output_csv_251_500, index=False)
238
+ print(f"\nSaved {len(rows)} cases to {output_csv_251_500}")
239
+
240
+ print(f"\nFat Percentage Summary (251-500):")
241
+ for col in fat_cols:
242
+ values = df[col].values
243
+ mean_val = np.mean(values) # type: ignore
244
+ std_val = np.std(values) # type: ignore
245
+ print(f"{col}: {mean_val:.2f} ± {std_val:.2f} %")
246
+
247
+ save_mean_std_stats(df, fat_cols, output_csv_251_500.parent / "test_fat_mean_std.csv")
248
+ else:
249
+ print("No data processed for 251-500!")
250
+
251
+ def main():
252
+ """Main function to process both datasets."""
253
+ print("FATTY PERCENTAGE ANALYSIS")
254
+ print("Computing fat percentage (HU <= -20) for 9 muscle labels")
255
+ print("="*60)
256
+
257
+ process_100_120_dataset()
258
+
259
+ process_251_500_dataset()
260
+
261
+ print("\n" + "="*60)
262
+ print("ANALYSIS COMPLETE")
263
+ print("="*60)
264
+ print(f"Results saved to:")
265
+ print(f" - {output_csv_100_120} (cases 100-120)")
266
+ print(f" - {output_csv_251_500} (cases 251-500)")
267
+
268
+ if __name__ == "__main__":
269
+ main()