Spine-Analysis-Pipeline / scripts /model_dev_pred_fatty_analysis.py
onlineinfoh's picture
add all scripts
9ee6a3d
#!/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()