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

correlation viz

Browse files
Files changed (1) hide show
  1. scripts/correlation_plot.py +331 -0
scripts/correlation_plot.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Create correlation plots for muscle fat vs Cobb angles
4
+ """
5
+
6
+ import pandas as pd # type: ignore
7
+ import numpy as np # type: ignore
8
+ import matplotlib.pyplot as plt # type: ignore
9
+ import seaborn as sns # type: ignore
10
+ from pathlib import Path
11
+ from scipy.stats import pearsonr # type: ignore
12
+ import argparse
13
+
14
+ plt.style.use('seaborn-v0_8')
15
+ sns.set_palette("husl")
16
+
17
+ dev_correlation_csv = Path("../pearson_correlation/dev_cobb_corr/fatty_atrophy_thoracic_correlations.csv")
18
+ test_correlation_csv = Path("../pearson_correlation/test_cobb_corr/fatty_atrophy_thoracic_correlations.csv")
19
+
20
+ dev_fatty_csv = Path("../fatty_data/dev_fat.csv")
21
+ test_fatty_csv = Path("../fatty_data/test_fat.csv")
22
+
23
+ dev_cobb_csv = Path("../cobb_angles/dev_cobb.csv")
24
+ test_cobb_csv = Path("../cobb_angles/test_cobb.csv")
25
+
26
+ def load_correlation_data(dataset="dev"):
27
+ """Load the correlation data from the CSV file."""
28
+ if dataset == "dev":
29
+ csv_path = dev_correlation_csv
30
+ else:
31
+ csv_path = test_correlation_csv
32
+
33
+ if not csv_path.exists():
34
+ print(f"Error: Correlation file not found at {csv_path}")
35
+ return None
36
+
37
+ df = pd.read_csv(csv_path)
38
+ print(f"Loaded correlation data: {len(df)} muscles")
39
+ return df
40
+
41
+ def create_dev_correlation_scatter(df):
42
+ """Create a scatter plot for development dataset (100-120)."""
43
+
44
+ fatty_df = pd.read_csv(dev_fatty_csv)
45
+ manual_cobb_df = pd.read_csv(dev_cobb_csv, sep='\t', header=None) # type: ignore
46
+
47
+ thor_avg = np.round(manual_cobb_df.mean(axis=1)).astype(int)
48
+
49
+ fatty_manual = fatty_df[fatty_df['case_id'].str.isdigit()].copy()
50
+ fatty_manual['case_id'] = pd.to_numeric(fatty_manual['case_id']) # type: ignore
51
+
52
+ fig, ax = plt.subplots(figsize=(14, 8)) # type: ignore
53
+ fig.patch.set_facecolor('#f8f9fa')
54
+ ax.set_facecolor('#ffffff')
55
+
56
+ muscle_cols = [col for col in fatty_manual.columns if col.endswith('_fat_pct')]
57
+
58
+ trapezius_col = None
59
+ for col in muscle_cols:
60
+ if 'trapezius' in col.lower():
61
+ trapezius_col = col
62
+ break
63
+
64
+ if trapezius_col is None:
65
+ print("Trapezius muscle not found in the data")
66
+ return None, None
67
+
68
+ colors = ['#1f77b4'] # Blue color for Trapezius
69
+
70
+ col = trapezius_col
71
+
72
+ muscle_data = pd.to_numeric(fatty_manual[col], errors='coerce').values # type: ignore
73
+ cobb_data = thor_avg[:len(muscle_data)]
74
+
75
+ valid_mask = ~(np.isnan(muscle_data) | np.isnan(cobb_data)) # type: ignore
76
+ muscle_clean = muscle_data[valid_mask]
77
+ cobb_clean = cobb_data[valid_mask]
78
+
79
+ if len(muscle_clean) > 1: # Need at least 2 points
80
+
81
+ muscle_name = col.replace('_fat_pct', '').replace('_', ' ').title()
82
+
83
+ ax.scatter(muscle_clean, cobb_clean, color=colors[0], # type: ignore
84
+ label=muscle_name, s=60, alpha=0.7, edgecolors='black', linewidth=0.5)
85
+
86
+ z = np.polyfit(muscle_clean, cobb_clean, 1)
87
+ p = np.poly1d(z)
88
+ ax.plot(muscle_clean, p(muscle_clean), color=colors[0], # type: ignore
89
+ linestyle='-', alpha=0.8, linewidth=2)
90
+
91
+ muscle_name = col.replace('_fat_pct', '')
92
+ correlation_row = df[df['Muscle'] == muscle_name]
93
+ if not correlation_row.empty:
94
+ r = correlation_row['Correlation'].iloc[0]
95
+ p_val = correlation_row['P_Value'].iloc[0]
96
+ else:
97
+
98
+ r, p_val = pearsonr(muscle_clean, cobb_clean) # type: ignore
99
+
100
+ ax.set_xlabel('Fat Percentage (%)', fontsize=12, fontweight='bold')
101
+ ax.set_ylabel('Thoracic Cobb Angle (deg)', fontsize=12, fontweight='bold')
102
+ ax.set_title('Trapezius Muscle Fat Percentage vs Thoracic Cobb Angle\n(n = 21 cases)',
103
+ fontsize=14, fontweight='bold', pad=20)
104
+
105
+ ax.grid(True, alpha=0.3, color='gray', linestyle='-', linewidth=0.5)
106
+
107
+ for spine in ax.spines.values():
108
+ spine.set_edgecolor('#333333')
109
+ spine.set_linewidth(1.5)
110
+
111
+ plt.tight_layout()
112
+
113
+ output_path = "../pearson_correlation/dev_cobb_corr/muscle_correlation_scatter.png"
114
+ plt.savefig(output_path, dpi=300, bbox_inches='tight',
115
+ facecolor='white', edgecolor='none')
116
+ print(f"Saved correlation scatter plot to: {output_path}")
117
+
118
+ return fig, ax
119
+
120
+ def create_test_correlation_scatter(df):
121
+ """Create a scatter plot for test dataset (251-500)."""
122
+
123
+ fatty_df = pd.read_csv(test_fatty_csv)
124
+ cobb_df = pd.read_csv(test_cobb_csv, header=None, names=['cobb_angle']) # type: ignore
125
+
126
+ fatty_df = fatty_df[fatty_df['case_id'] != 'Mean ± SD'].copy()
127
+ fatty_df = fatty_df[pd.to_numeric(fatty_df['case_id'], errors='coerce').notna()] # type: ignore
128
+ fatty_df['case_id'] = fatty_df['case_id'].astype(int)
129
+
130
+ n_cases = min(len(cobb_df), len(fatty_df))
131
+ print(f"Using {n_cases} cases for test correlation analysis")
132
+
133
+ cobb_values = cobb_df.iloc[:n_cases, 0].values # Get the first column as numpy array
134
+ fat_values = fatty_df.iloc[:n_cases]
135
+
136
+ trapezius_col = None
137
+ for col in fat_values.columns:
138
+ if 'trapezius' in col.lower() and col.endswith('_fat_pct'):
139
+ trapezius_col = col
140
+ break
141
+
142
+ if trapezius_col is None:
143
+ print("Trapezius muscle not found in the test data")
144
+ return None, None
145
+
146
+ trapezius_data = pd.to_numeric(fat_values[trapezius_col], errors='coerce').values # type: ignore
147
+ cobb_data = cobb_values
148
+
149
+ valid_mask = ~(np.isnan(trapezius_data) | np.isnan(cobb_data)) # type: ignore
150
+ trapezius_clean = trapezius_data[valid_mask]
151
+ cobb_clean = cobb_data[valid_mask]
152
+
153
+ print(f"Valid data points: {len(trapezius_clean)}")
154
+ print(f"Trapezius range: {trapezius_clean.min():.2f} to {trapezius_clean.max():.2f}")
155
+ print(f"Cobb range: {cobb_clean.min():.1f} to {cobb_clean.max():.1f}")
156
+
157
+ fig, ax = plt.subplots(figsize=(14, 8)) # type: ignore
158
+ fig.patch.set_facecolor('#f8f9fa')
159
+ ax.set_facecolor('#ffffff')
160
+
161
+ ax.scatter(trapezius_clean, cobb_clean, color='#1f77b4', s=60, alpha=0.7, # type: ignore
162
+ edgecolors='black', linewidth=0.5)
163
+
164
+ z = np.polyfit(trapezius_clean, cobb_clean, 1)
165
+ p = np.poly1d(z)
166
+ ax.plot(trapezius_clean, p(trapezius_clean), color='#1f77b4', # type: ignore
167
+ linestyle='-', alpha=0.8, linewidth=2)
168
+
169
+ muscle_name = trapezius_col.replace('_fat_pct', '')
170
+ correlation_row = df[df['Muscle'] == muscle_name]
171
+ if not correlation_row.empty:
172
+ r = correlation_row['Correlation'].iloc[0]
173
+ p_val = correlation_row['P_Value'].iloc[0]
174
+ else:
175
+
176
+ r, p_val = pearsonr(trapezius_clean, cobb_clean) # type: ignore
177
+
178
+ ax.set_xlabel('Trapezius Fat Percentage (%)', fontsize=12, fontweight='bold')
179
+ ax.set_ylabel('Thoracic Cobb Angle (deg)', fontsize=12, fontweight='bold')
180
+ ax.set_title(f'Trapezius Muscle Fat Percentage vs Thoracic Cobb Angle\n(n = {len(trapezius_clean)} cases)',
181
+ fontsize=14, fontweight='bold', pad=20)
182
+
183
+ ax.grid(True, alpha=0.3, color='gray', linestyle='-', linewidth=0.5)
184
+
185
+ for spine in ax.spines.values():
186
+ spine.set_edgecolor('#333333')
187
+ spine.set_linewidth(1.5)
188
+
189
+ plt.tight_layout()
190
+
191
+ output_path = "../pearson_correlation/test_cobb_corr/trapezius_fat_vs_thoracic_cobb_250_cases.png"
192
+ plt.savefig(output_path, dpi=300, bbox_inches='tight',
193
+ facecolor='white', edgecolor='none')
194
+ print(f"Saved test correlation plot to: {output_path}")
195
+
196
+ return fig, ax
197
+
198
+ def create_aggregate_plot(df, dataset="dev"):
199
+ """Create a 3x3 aggregate plot showing all 9 muscles."""
200
+
201
+ if dataset == "dev":
202
+ fatty_df = pd.read_csv(dev_fatty_csv)
203
+ cobb_df = pd.read_csv(dev_cobb_csv, sep='\t', header=None) # type: ignore
204
+
205
+ cobb_data = np.round(cobb_df.mean(axis=1)).astype(int)
206
+ n_cases = 21
207
+ else:
208
+ fatty_df = pd.read_csv(test_fatty_csv)
209
+ cobb_df = pd.read_csv(test_cobb_csv, header=None, names=['cobb_angle']) # type: ignore
210
+ cobb_data = cobb_df.iloc[:, 0].values
211
+ n_cases = 250
212
+
213
+ fatty_df = fatty_df[fatty_df['case_id'] != 'Mean ± SD'].copy()
214
+ fatty_df = fatty_df[pd.to_numeric(fatty_df['case_id'], errors='coerce').notna()] # type: ignore
215
+ fatty_df['case_id'] = fatty_df['case_id'].astype(int)
216
+
217
+ muscle_cols = [col for col in fatty_df.columns if col.endswith('_fat_pct')]
218
+
219
+ fig, axes = plt.subplots(3, 3, figsize=(18, 15)) # type: ignore
220
+ fig.patch.set_facecolor('#f8f9fa')
221
+
222
+ axes_flat = axes.flatten()
223
+
224
+ colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
225
+ '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22']
226
+
227
+ for i, col in enumerate(muscle_cols):
228
+ if i >= 9: # Only plot first 9 muscles
229
+ break
230
+
231
+ ax = axes_flat[i]
232
+ ax.set_facecolor('#ffffff')
233
+
234
+ muscle_data = pd.to_numeric(fatty_df[col], errors='coerce').values # type: ignore
235
+ cobb_clean = cobb_data[:len(muscle_data)]
236
+
237
+ valid_mask = ~(np.isnan(muscle_data) | np.isnan(cobb_clean)) # type: ignore
238
+ muscle_clean = muscle_data[valid_mask]
239
+ cobb_clean = cobb_clean[valid_mask]
240
+
241
+ if len(muscle_clean) > 1:
242
+
243
+ muscle_name = col.replace('_fat_pct', '').replace('_', ' ').title()
244
+
245
+ ax.scatter(muscle_clean, cobb_clean, color=colors[i], # type: ignore
246
+ s=40, alpha=0.7, edgecolors='black', linewidth=0.3)
247
+
248
+ if len(muscle_clean) > 1:
249
+ z = np.polyfit(muscle_clean, cobb_clean, 1)
250
+ p = np.poly1d(z)
251
+ ax.plot(muscle_clean, p(muscle_clean), color=colors[i], # type: ignore
252
+ linestyle='-', alpha=0.8, linewidth=1.5)
253
+
254
+ muscle_name_csv = col.replace('_fat_pct', '')
255
+ correlation_row = df[df['Muscle'] == muscle_name_csv]
256
+ if not correlation_row.empty:
257
+ r = correlation_row['Correlation'].iloc[0]
258
+ p_val = correlation_row['P_Value'].iloc[0]
259
+ else:
260
+ r, p_val = pearsonr(muscle_clean, cobb_clean) # type: ignore
261
+
262
+ ax.set_title(f'{muscle_name}\nr = {r:.3f}', fontsize=10, fontweight='bold')
263
+
264
+ ax.set_xlabel('Fat %', fontsize=8)
265
+ ax.set_ylabel('Cobb Angle (deg)', fontsize=8)
266
+ ax.grid(True, alpha=0.3, linewidth=0.5)
267
+
268
+ for spine in ax.spines.values():
269
+ spine.set_edgecolor('#333333')
270
+ spine.set_linewidth(0.8)
271
+
272
+ for i in range(len(muscle_cols), 9):
273
+ axes_flat[i].set_visible(False)
274
+
275
+ plt.tight_layout()
276
+
277
+ output_path = f"../pearson_correlation/{dataset}_cobb_corr/aggregate_muscle_correlations.png"
278
+ plt.savefig(output_path, dpi=300, bbox_inches='tight',
279
+ facecolor='white', edgecolor='none')
280
+ print(f"Saved aggregate plot to: {output_path}")
281
+
282
+ return fig, axes
283
+
284
+ def main():
285
+ """Main function to create correlation plots."""
286
+ parser = argparse.ArgumentParser(description='Create muscle correlation plots')
287
+ parser.add_argument('--dataset', choices=['dev', 'test', 'both'], default='both',
288
+ help='Which dataset to plot (dev, test, or both)')
289
+ parser.add_argument('--plot-type', choices=['trapezius', 'aggregate', 'both'], default='both',
290
+ help='Which plot type to create (trapezius, aggregate, or both)')
291
+ args = parser.parse_args()
292
+
293
+ print("=== MUSCLE CORRELATION VISUALIZATION ===")
294
+
295
+ if args.dataset in ['dev', 'both']:
296
+ print("\n=== DEVELOPMENT DATASET (100-120) ===")
297
+ df_dev = load_correlation_data("dev")
298
+ if df_dev is not None:
299
+ if args.plot_type in ['trapezius', 'both']:
300
+ fig1, ax1 = create_dev_correlation_scatter(df_dev)
301
+ if fig1 is not None:
302
+ print("Development trapezius plot created successfully")
303
+ plt.show()
304
+
305
+ if args.plot_type in ['aggregate', 'both']:
306
+ fig2, ax2 = create_aggregate_plot(df_dev, "dev")
307
+ if fig2 is not None:
308
+ print("Development aggregate plot created successfully")
309
+ plt.show()
310
+
311
+ if args.dataset in ['test', 'both']:
312
+ print("\n=== TEST DATASET (251-500) ===")
313
+ df_test = load_correlation_data("test")
314
+ if df_test is not None:
315
+ if args.plot_type in ['trapezius', 'both']:
316
+ fig3, ax3 = create_test_correlation_scatter(df_test)
317
+ if fig3 is not None:
318
+ print("Test trapezius plot created successfully")
319
+ plt.show()
320
+
321
+ if args.plot_type in ['aggregate', 'both']:
322
+ fig4, ax4 = create_aggregate_plot(df_test, "test")
323
+ if fig4 is not None:
324
+ print("Test aggregate plot created successfully")
325
+ plt.show()
326
+
327
+ print("\n=== VISUALIZATION COMPLETE ===")
328
+ print("Generated Pearson correlation scatter plots for muscle fat percentages vs thoracic Cobb angles")
329
+
330
+ if __name__ == "__main__":
331
+ main()