File size: 7,943 Bytes
c202fc8 | 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 | """
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) |