File size: 12,902 Bytes
1b1be04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ee6a3d
1b1be04
 
 
 
 
 
 
 
 
9ee6a3d
1b1be04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ee6a3d
1b1be04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#!/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()