Spine-Analysis-Pipeline / scripts /correlation_plot.py
onlineinfoh's picture
add all scripts
9ee6a3d
raw
history blame
12.9 kB
#!/usr/bin/env python3
"""
Create correlation plots for muscle fat vs Cobb angles
"""
import pandas as pd # type: ignore
import numpy as np # type: ignore
import matplotlib.pyplot as plt # type: ignore
import seaborn as sns # type: ignore
from pathlib import Path
from scipy.stats import pearsonr # type: ignore
import argparse
plt.style.use('seaborn-v0_8')
sns.set_palette("husl")
dev_correlation_csv = Path("../pearson_correlation/dev_cobb_corr/fatty_atrophy_thoracic_correlations.csv")
test_correlation_csv = Path("../pearson_correlation/test_cobb_corr/fatty_atrophy_thoracic_correlations.csv")
dev_fatty_csv = Path("../fatty_data/dev_fat.csv")
test_fatty_csv = Path("../fatty_data/test_fat.csv")
dev_cobb_csv = Path("../cobb_angles/dev_cobb.csv")
test_cobb_csv = Path("../cobb_angles/test_cobb.csv")
def load_correlation_data(dataset="dev"):
"""Load the correlation data from the CSV file."""
if dataset == "dev":
csv_path = dev_correlation_csv
else:
csv_path = test_correlation_csv
if not csv_path.exists():
print(f"Error: Correlation file not found at {csv_path}")
return None
df = pd.read_csv(csv_path)
print(f"Loaded correlation data: {len(df)} muscles")
return df
def create_dev_correlation_scatter(df):
"""Create a scatter plot for development dataset (100-120)."""
fatty_df = pd.read_csv(dev_fatty_csv)
manual_cobb_df = pd.read_csv(dev_cobb_csv, sep='\t', header=None) # type: ignore
thor_avg = np.round(manual_cobb_df.mean(axis=1)).astype(int)
fatty_manual = fatty_df[fatty_df['case_id'].str.isdigit()].copy()
fatty_manual['case_id'] = pd.to_numeric(fatty_manual['case_id']) # type: ignore
fig, ax = plt.subplots(figsize=(14, 8)) # type: ignore
fig.patch.set_facecolor('#f8f9fa')
ax.set_facecolor('#ffffff')
muscle_cols = [col for col in fatty_manual.columns if col.endswith('_fat_pct')]
trapezius_col = None
for col in muscle_cols:
if 'trapezius' in col.lower():
trapezius_col = col
break
if trapezius_col is None:
print("Trapezius muscle not found in the data")
return None, None
colors = ['#1f77b4']
col = trapezius_col
muscle_data = pd.to_numeric(fatty_manual[col], errors='coerce').values # type: ignore
cobb_data = thor_avg[:len(muscle_data)]
valid_mask = ~(np.isnan(muscle_data) | np.isnan(cobb_data)) # type: ignore
muscle_clean = muscle_data[valid_mask]
cobb_clean = cobb_data[valid_mask]
if len(muscle_clean) > 1:
muscle_name = col.replace('_fat_pct', '').replace('_', ' ').title()
ax.scatter(muscle_clean, cobb_clean, color=colors[0], # type: ignore
label=muscle_name, s=60, alpha=0.7, edgecolors='black', linewidth=0.5)
z = np.polyfit(muscle_clean, cobb_clean, 1)
p = np.poly1d(z)
ax.plot(muscle_clean, p(muscle_clean), color=colors[0], # type: ignore
linestyle='-', alpha=0.8, linewidth=2)
muscle_name = col.replace('_fat_pct', '')
correlation_row = df[df['Muscle'] == muscle_name]
if not correlation_row.empty:
r = correlation_row['Correlation'].iloc[0]
p_val = correlation_row['P_Value'].iloc[0]
else:
r, p_val = pearsonr(muscle_clean, cobb_clean) # type: ignore
ax.set_xlabel('Fat Percentage (%)', fontsize=12, fontweight='bold')
ax.set_ylabel('Thoracic Cobb Angle (deg)', fontsize=12, fontweight='bold')
ax.set_title('Trapezius Muscle Fat Percentage vs Thoracic Cobb Angle\n(n = 21 cases)',
fontsize=14, fontweight='bold', pad=20)
ax.grid(True, alpha=0.3, color='gray', linestyle='-', linewidth=0.5)
for spine in ax.spines.values():
spine.set_edgecolor('#333333')
spine.set_linewidth(1.5)
plt.tight_layout()
output_path = "../pearson_correlation/dev_cobb_corr/muscle_correlation_scatter.png"
plt.savefig(output_path, dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
print(f"Saved correlation scatter plot to: {output_path}")
return fig, ax
def create_test_correlation_scatter(df):
"""Create a scatter plot for test dataset (251-500)."""
fatty_df = pd.read_csv(test_fatty_csv)
cobb_df = pd.read_csv(test_cobb_csv, header=None, names=['cobb_angle']) # type: ignore
fatty_df = fatty_df[fatty_df['case_id'] != 'Mean ± SD'].copy()
fatty_df = fatty_df[pd.to_numeric(fatty_df['case_id'], errors='coerce').notna()] # type: ignore
fatty_df['case_id'] = fatty_df['case_id'].astype(int)
n_cases = min(len(cobb_df), len(fatty_df))
print(f"Using {n_cases} cases for test correlation analysis")
cobb_values = cobb_df.iloc[:n_cases, 0].values # Get the first column as numpy array
fat_values = fatty_df.iloc[:n_cases]
trapezius_col = None
for col in fat_values.columns:
if 'trapezius' in col.lower() and col.endswith('_fat_pct'):
trapezius_col = col
break
if trapezius_col is None:
print("Trapezius muscle not found in the test data")
return None, None
trapezius_data = pd.to_numeric(fat_values[trapezius_col], errors='coerce').values # type: ignore
cobb_data = cobb_values
valid_mask = ~(np.isnan(trapezius_data) | np.isnan(cobb_data)) # type: ignore
trapezius_clean = trapezius_data[valid_mask]
cobb_clean = cobb_data[valid_mask]
print(f"Valid data points: {len(trapezius_clean)}")
print(f"Trapezius range: {trapezius_clean.min():.2f} to {trapezius_clean.max():.2f}")
print(f"Cobb range: {cobb_clean.min():.1f} to {cobb_clean.max():.1f}")
fig, ax = plt.subplots(figsize=(14, 8)) # type: ignore
fig.patch.set_facecolor('#f8f9fa')
ax.set_facecolor('#ffffff')
ax.scatter(trapezius_clean, cobb_clean, color='#1f77b4', s=60, alpha=0.7, # type: ignore
edgecolors='black', linewidth=0.5)
z = np.polyfit(trapezius_clean, cobb_clean, 1)
p = np.poly1d(z)
ax.plot(trapezius_clean, p(trapezius_clean), color='#1f77b4', # type: ignore
linestyle='-', alpha=0.8, linewidth=2)
muscle_name = trapezius_col.replace('_fat_pct', '')
correlation_row = df[df['Muscle'] == muscle_name]
if not correlation_row.empty:
r = correlation_row['Correlation'].iloc[0]
p_val = correlation_row['P_Value'].iloc[0]
else:
r, p_val = pearsonr(trapezius_clean, cobb_clean) # type: ignore
ax.set_xlabel('Trapezius Fat Percentage (%)', fontsize=12, fontweight='bold')
ax.set_ylabel('Thoracic Cobb Angle (deg)', fontsize=12, fontweight='bold')
ax.set_title(f'Trapezius Muscle Fat Percentage vs Thoracic Cobb Angle\n(n = {len(trapezius_clean)} cases)',
fontsize=14, fontweight='bold', pad=20)
ax.grid(True, alpha=0.3, color='gray', linestyle='-', linewidth=0.5)
for spine in ax.spines.values():
spine.set_edgecolor('#333333')
spine.set_linewidth(1.5)
plt.tight_layout()
output_path = "../pearson_correlation/test_cobb_corr/trapezius_fat_vs_thoracic_cobb_250_cases.png"
plt.savefig(output_path, dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
print(f"Saved test correlation plot to: {output_path}")
return fig, ax
def create_aggregate_plot(df, dataset="dev"):
"""Create a 3x3 aggregate plot showing all 9 muscles."""
if dataset == "dev":
fatty_df = pd.read_csv(dev_fatty_csv)
cobb_df = pd.read_csv(dev_cobb_csv, sep='\t', header=None) # type: ignore
cobb_data = np.round(cobb_df.mean(axis=1)).astype(int)
n_cases = 21
else:
fatty_df = pd.read_csv(test_fatty_csv)
cobb_df = pd.read_csv(test_cobb_csv, header=None, names=['cobb_angle']) # type: ignore
cobb_data = cobb_df.iloc[:, 0].values
n_cases = 250
fatty_df = fatty_df[fatty_df['case_id'] != 'Mean ± SD'].copy()
fatty_df = fatty_df[pd.to_numeric(fatty_df['case_id'], errors='coerce').notna()] # type: ignore
fatty_df['case_id'] = fatty_df['case_id'].astype(int)
muscle_cols = [col for col in fatty_df.columns if col.endswith('_fat_pct')]
fig, axes = plt.subplots(3, 3, figsize=(18, 15)) # type: ignore
fig.patch.set_facecolor('#f8f9fa')
axes_flat = axes.flatten()
colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22']
for i, col in enumerate(muscle_cols):
if i >= 9:
break
ax = axes_flat[i]
ax.set_facecolor('#ffffff')
muscle_data = pd.to_numeric(fatty_df[col], errors='coerce').values # type: ignore
cobb_clean = cobb_data[:len(muscle_data)]
valid_mask = ~(np.isnan(muscle_data) | np.isnan(cobb_clean)) # type: ignore
muscle_clean = muscle_data[valid_mask]
cobb_clean = cobb_clean[valid_mask]
if len(muscle_clean) > 1:
muscle_name = col.replace('_fat_pct', '').replace('_', ' ').title()
ax.scatter(muscle_clean, cobb_clean, color=colors[i], # type: ignore
s=40, alpha=0.7, edgecolors='black', linewidth=0.3)
if len(muscle_clean) > 1:
z = np.polyfit(muscle_clean, cobb_clean, 1)
p = np.poly1d(z)
ax.plot(muscle_clean, p(muscle_clean), color=colors[i], # type: ignore
linestyle='-', alpha=0.8, linewidth=1.5)
muscle_name_csv = col.replace('_fat_pct', '')
correlation_row = df[df['Muscle'] == muscle_name_csv]
if not correlation_row.empty:
r = correlation_row['Correlation'].iloc[0]
p_val = correlation_row['P_Value'].iloc[0]
else:
r, p_val = pearsonr(muscle_clean, cobb_clean) # type: ignore
ax.set_title(f'{muscle_name}\nr = {r:.3f}', fontsize=10, fontweight='bold')
ax.set_xlabel('Fat %', fontsize=8)
ax.set_ylabel('Cobb Angle (deg)', fontsize=8)
ax.grid(True, alpha=0.3, linewidth=0.5)
for spine in ax.spines.values():
spine.set_edgecolor('#333333')
spine.set_linewidth(0.8)
for i in range(len(muscle_cols), 9):
axes_flat[i].set_visible(False)
plt.tight_layout()
output_path = f"../pearson_correlation/{dataset}_cobb_corr/aggregate_muscle_correlations.png"
plt.savefig(output_path, dpi=300, bbox_inches='tight',
facecolor='white', edgecolor='none')
print(f"Saved aggregate plot to: {output_path}")
return fig, axes
def main():
"""Main function to create correlation plots."""
parser = argparse.ArgumentParser(description='Create muscle correlation plots')
parser.add_argument('--dataset', choices=['dev', 'test', 'both'], default='both',
help='Which dataset to plot (dev, test, or both)')
parser.add_argument('--plot-type', choices=['trapezius', 'aggregate', 'both'], default='both',
help='Which plot type to create (trapezius, aggregate, or both)')
args = parser.parse_args()
print("=== MUSCLE CORRELATION VISUALIZATION ===")
if args.dataset in ['dev', 'both']:
print("\n=== DEVELOPMENT DATASET (100-120) ===")
df_dev = load_correlation_data("dev")
if df_dev is not None:
if args.plot_type in ['trapezius', 'both']:
fig1, ax1 = create_dev_correlation_scatter(df_dev)
if fig1 is not None:
print("Development trapezius plot created successfully")
plt.show()
if args.plot_type in ['aggregate', 'both']:
fig2, ax2 = create_aggregate_plot(df_dev, "dev")
if fig2 is not None:
print("Development aggregate plot created successfully")
plt.show()
if args.dataset in ['test', 'both']:
print("\n=== TEST DATASET (251-500) ===")
df_test = load_correlation_data("test")
if df_test is not None:
if args.plot_type in ['trapezius', 'both']:
fig3, ax3 = create_test_correlation_scatter(df_test)
if fig3 is not None:
print("Test trapezius plot created successfully")
plt.show()
if args.plot_type in ['aggregate', 'both']:
fig4, ax4 = create_aggregate_plot(df_test, "test")
if fig4 is not None:
print("Test aggregate plot created successfully")
plt.show()
print("\n=== VISUALIZATION COMPLETE ===")
print("Generated Pearson correlation scatter plots for muscle fat percentages vs thoracic Cobb angles")
if __name__ == "__main__":
main()