Download analysis/02_main_study/06_practice_effects.py from sciminds/same-words-different-judgements: direct link, hf CLI and curl.
- Browser
- Download file 7.94 kB
-
https://huggingface.co/datasets/sciminds/same-words-different-judgements/resolve/main/analysis/02_main_study/06_practice_effects.py
- Command line
-
hf download hf://datasets/sciminds/same-words-different-judgements/analysis/02_main_study/06_practice_effects.py
-
curl -L -o 06_practice_effects.py https://huggingface.co/datasets/sciminds/same-words-different-judgements/resolve/main/analysis/02_main_study/06_practice_effects.py
7.94 kB
| """ | |
| PRACTICE EFFECTS: TRIAL DURATION OVER TRIALS (LMM VERSION) | |
| ============================================================ | |
| Analyzes whether trial completion time changed significantly over trials | |
| using a linear mixed-effects model matching the fatigue analysis (H9a). | |
| Model: log(Duration) ~ trial_z * modality + (1|participantID) + (1|PromptID) | |
| """ | |
| import pandas as pd | |
| import numpy as np | |
| import polars as pl | |
| from scipy import stats | |
| from pymer4.models import lmer | |
| import matplotlib.pyplot as plt | |
| import warnings | |
| import sys, os | |
| sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "common")) | |
| from _config import DATA_DIR, FIGURES_DIR, save_table | |
| warnings.filterwarnings('ignore') | |
| # ============================================================================ | |
| # LOAD DATA (wide format — duration is trial-level, not clip-level) | |
| # ============================================================================ | |
| audio_data = pd.read_csv(f"{DATA_DIR}/audio_data_table_clean.csv") | |
| text_data = pd.read_csv(f"{DATA_DIR}/text_data_table_clean.csv") | |
| audio_data = audio_data[audio_data['IsAttentionCheck'] == False].copy() | |
| text_data = text_data[text_data['IsAttentionCheck'] == False].copy() | |
| audio_data['modality'] = 'audio' | |
| text_data['modality'] = 'text' | |
| combined = pd.concat([audio_data, text_data], ignore_index=True) | |
| combined = combined.dropna(subset=['totalTaskDurationTime', 'TrialNumber']).copy() | |
| # ============================================================================ | |
| # PREPARE VARIABLES (mirrors H9a) | |
| # ============================================================================ | |
| combined['log_duration'] = np.log(combined['totalTaskDurationTime']) | |
| combined['trial_z'] = (combined['TrialNumber'] - combined['TrialNumber'].mean()) / combined['TrialNumber'].std() | |
| combined = combined.rename(columns={'ParticipantID': 'participantID'}) | |
| print("=" * 60) | |
| print("PRACTICE EFFECTS: TRIAL DURATION OVER TRIALS (LMM)") | |
| print("=" * 60) | |
| n_audio = len(combined[combined['modality'] == 'audio']) | |
| n_text = len(combined[combined['modality'] == 'text']) | |
| n_audio_p = combined[combined['modality'] == 'audio']['participantID'].nunique() | |
| n_text_p = combined[combined['modality'] == 'text']['participantID'].nunique() | |
| print(f"\nAudio: {n_audio} observations, {n_audio_p} participants") | |
| print(f"Text: {n_text} observations, {n_text_p} participants") | |
| print(f"Trial range: {combined['TrialNumber'].min()} - {combined['TrialNumber'].max()}") | |
| # ============================================================================ | |
| # MODEL: log(Duration) ~ trial_z * modality + (1|participantID) + (1|PromptID) | |
| # ============================================================================ | |
| print("\n" + "-" * 60) | |
| print("MODEL: log(Duration) ~ trial_z * modality + (1|participantID) + (1|PromptID)") | |
| print("-" * 60) | |
| try: | |
| pl_df = pl.DataFrame(combined) | |
| model = lmer('log_duration ~ trial_z * modality + (1|participantID) + (1|PromptID)', data=pl_df) | |
| model.fit(summarize=False) | |
| print("\nLMER fitted successfully") | |
| print(model.result_fit) | |
| print(model.ranef) | |
| except Exception as e: | |
| print(f"LMER failed: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| # ============================================================================ | |
| # SIMPLE EFFECTS: Each modality separately | |
| # ============================================================================ | |
| print("\n" + "-" * 60) | |
| print("SIMPLE EFFECTS: Audio Only") | |
| print("-" * 60) | |
| audio_only = combined[combined['modality'] == 'audio'].copy() | |
| try: | |
| pl_df = pl.DataFrame(audio_only) | |
| model_audio = lmer('log_duration ~ trial_z + (1|participantID) + (1|PromptID)', data=pl_df) | |
| model_audio.fit(summarize=False) | |
| print(model_audio.result_fit) | |
| except Exception as e: | |
| print(f"Audio model failed: {e}") | |
| print("\n" + "-" * 60) | |
| print("SIMPLE EFFECTS: Text Only") | |
| print("-" * 60) | |
| text_only = combined[combined['modality'] == 'text'].copy() | |
| try: | |
| pl_df = pl.DataFrame(text_only) | |
| model_text = lmer('log_duration ~ trial_z + (1|participantID) + (1|PromptID)', data=pl_df) | |
| model_text.fit(summarize=False) | |
| print(model_text.result_fit) | |
| except Exception as e: | |
| print(f"Text model failed: {e}") | |
| save_table({"omnibus": model.result_fit, "audio": model_audio.result_fit, | |
| "text": model_text.result_fit}, | |
| "02_main_study", "practice_effects.csv") | |
| # ============================================================================ | |
| # BACK-TRANSFORM: % change per SD on original scale | |
| # ============================================================================ | |
| print("\n" + "-" * 60) | |
| print("BACK-TRANSFORMED EFFECTS (% change per SD of trial number)") | |
| print("-" * 60) | |
| for label, m in [("Audio", model_audio), ("Text", model_text)]: | |
| try: | |
| row = m.result_fit.filter(pl.col('term') == 'trial_z') | |
| beta = row['estimate'][0] | |
| ci_lo = row['conf_low'][0] | |
| ci_hi = row['conf_high'][0] | |
| pct = (np.exp(beta) - 1) * 100 | |
| pct_lo = (np.exp(ci_lo) - 1) * 100 | |
| pct_hi = (np.exp(ci_hi) - 1) * 100 | |
| print(f"\n{label}:") | |
| print(f" b = {beta:.4f}, 95% CI [{ci_lo:.4f}, {ci_hi:.4f}]") | |
| print(f" -> {pct:.1f}% change per SD [{pct_lo:.1f}%, {pct_hi:.1f}%]") | |
| except Exception as e: | |
| print(f" Back-transform failed for {label}: {e}") | |
| # ============================================================================ | |
| # DESCRIPTIVE: Baseline trial durations per modality | |
| # ============================================================================ | |
| print("\n" + "-" * 60) | |
| print("DESCRIPTIVE: Trial Duration by Modality") | |
| print("-" * 60) | |
| for mod in ['audio', 'text']: | |
| dur = combined[combined['modality'] == mod]['totalTaskDurationTime'] / 1000 | |
| print(f"\n{mod.capitalize()}:") | |
| print(f" Mean: {dur.mean():.1f} s, SD: {dur.std():.1f} s, Median: {dur.median():.1f} s") | |
| # ============================================================================ | |
| # VISUALIZATION | |
| # ============================================================================ | |
| print("\n" + "-" * 60) | |
| print("GENERATING VISUALIZATION") | |
| print("-" * 60) | |
| # Use the already-loaded wide-format data | |
| audio_wide = audio_data | |
| text_wide = text_data | |
| fig, axes = plt.subplots(1, 2, figsize=(12, 5)) | |
| # Plot 1: Mean duration by trial number | |
| ax = axes[0] | |
| for df, name, color in [(audio_wide, 'Audio', 'blue'), (text_wide, 'Text', 'orange')]: | |
| trial_means = df.groupby('TrialNumber')['totalTaskDurationTime'].mean() / 1000 | |
| trial_se = df.groupby('TrialNumber')['totalTaskDurationTime'].sem() / 1000 | |
| ax.errorbar(trial_means.index, trial_means.values, yerr=trial_se.values, | |
| marker='o', label=name, color=color, alpha=0.7, capsize=3) | |
| ax.set_xlabel('Trial Number') | |
| ax.set_ylabel('Mean Duration (seconds)') | |
| ax.set_title('Mean Trial Duration by Trial Number (+/-SE)') | |
| ax.legend() | |
| # Plot 2: Per-participant slopes (supplementary) | |
| ax = axes[1] | |
| for df, name, color in [(audio_wide, 'Audio', 'blue'), (text_wide, 'Text', 'orange')]: | |
| slopes = [] | |
| for pid in df['ParticipantID'].unique(): | |
| pdata = df[df['ParticipantID'] == pid] | |
| if len(pdata) > 2: | |
| slope, _, _, _, _ = stats.linregress( | |
| pdata['TrialNumber'], | |
| pdata['totalTaskDurationTime'] / 1000 | |
| ) | |
| slopes.append(slope) | |
| ax.hist(slopes, bins=20, alpha=0.5, label=f'{name} (n={len(slopes)})', color=color) | |
| ax.axvline(np.mean(slopes), color=color, linestyle='--', linewidth=2) | |
| ax.set_xlabel('Slope (seconds per trial)') | |
| ax.set_ylabel('Number of Participants') | |
| ax.set_title('Per-Participant Duration Slopes') | |
| ax.legend() | |
| ax.axvline(0, color='black', linestyle='-', linewidth=1, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(FIGURES_DIR / "trial_duration_analysis.png", dpi=150, bbox_inches='tight') | |
| print(f"Saved visualization to: {FIGURES_DIR}/trial_duration_analysis.png") | |
| plt.close() | |
| print("\n" + "=" * 60) | |
| print("DONE") | |
| print("=" * 60) |