-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmpnet_efa.py
More file actions
2986 lines (2465 loc) · 120 KB
/
Copy pathmpnet_efa.py
File metadata and controls
2986 lines (2465 loc) · 120 KB
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ==============================================================================
# Semantic Factor Analysis (SFA) — Yanitski, D. and Westbury, C. (2025)
# ==============================================================================
#
# Validates psychological scales by comparing factor structures extracted from
# LLM embeddings against those extracted from human response data.
#
# PIPELINE
# --------
# 1. Load scale definition (scale_items/{SCALE}_items.csv) containing item
# codes, text, theoretical factor labels, and scoring direction (+1/-1).
# Optionally load empirical Likert-scale responses (scale_responses/).
#
# 2. Obtain high-dimensional embeddings for each item from a pre-trained
# sentence-transformer (dwulff/mpnet-personality). Embeddings may be loaded
# from cache or generated on the fly.
#
# 3. Apply atomic-reversed encoding: multiply each item's embedding by its
# scoring direction (+1 or -1), then L2-normalize. This encodes reverse-
# scored items as pointing in the opposite semantic direction.
#
# 4. Compute the item-by-item cosine similarity matrix from the signed
# embeddings. This matrix serves as a pseudo-correlation matrix for EFA.
#
# 5. Run exploratory factor analysis (EFA) on the cosine similarity matrix:
# a. Parallel analysis (95th-percentile, 100 iterations) to determine
# the number of factors to retain.
# b. Factor extraction (default: minres/ULS) with oblique rotation
# (default: oblimin) to allow correlated factors.
# c. Compute diagnostics: KMO sampling adequacy, Bartlett sphericity,
# DAAL (Dominant Average Absolute Loading) for factor-to-construct
# assignment, and Tucker congruence (phi) against theoretical factors.
#
# 6. Repeat step 5 on the empirical Pearson correlation matrix (traditional
# EFA) when human response data is available. Reverse-scored items are
# reflected before computing correlations.
#
# 7. Generate comparison visualizations between embedding-based and empirical
# factor structures: scree plots, loading heatmaps, 2-D loading plots,
# Tucker congruence heatmaps, within- vs between-construct similarity
# violin plots, and t-SNE scatter plots.
#
# 8. Compute matrix-level agreement: Pearson correlation and Mantel test
# (10 000 permutations) between the LLM cosine similarity matrix and the
# human inter-item correlation matrix.
#
# 9. Automatic factor naming via three methods:
# Method 1 — Feed top-loading items to an instruct LLM (Qwen3-235B-A22B).
# Method 2 — Find nearest-neighbour words to the factor centroid in
# embedding space, then summarise with the instruct LLM.
# Method 3 — (optional) Greedy token prediction from a base LLM.
#
# CONFIGURATION
# -------------
# All user-settable parameters (model, scale list, EFA settings, feature
# flags) are grouped in the first few cells. Key variables:
# MODEL_NAMES — sentence-transformer model(s) to use
# SCALE_NAMES — which scale(s) to analyse
# N_FACTORS — None for automatic (parallel analysis) or int
# ROTATION_METHOD — 'oblimin', 'promax', 'varimax', etc.
# EXTRACTION_METHOD — 'minres', 'ml', 'principal'
# ENABLE_FACTOR_NAMING — toggle LLM-based factor naming
# ENABLE_METHOD_3 — toggle base-model token-prediction naming
#
# INPUT / OUTPUT
# --------------
# Inputs:
# scale_items/{SCALE}_items.csv — code, item, factor, scoring
# scale_responses/{SCALE}_data.csv — participants x items (optional)
# embeddings/{SCALE}_items_{SIZE}.npz — pregenerated item embeddings
# embeddings/{N}_constructs_{SIZE}.npz— pregenerated word embeddings
#
# Outputs (written to results/{SCALE}/):
# analysis_log.txt — full console log
# visualizations_{SIZE}.png — 6-panel diagnostic plot
# comparison_loadings.png — side-by-side loading heatmaps
# comparison_tucker.png — Tucker congruence comparison
# comparison_within_between.png — violin plots
# {SCALE}_embeddings_vs_empirical_*.png — scree, t-SNE, correlation plots
# ==============================================================================
import os
import sys
import re
import glob
import importlib
import subprocess
import warnings
from pathlib import Path
from datetime import datetime
import numpy as np
import pandas as pd
import torch
from sentence_transformers import SentenceTransformer
from openai import OpenAI
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.axes_grid1 import make_axes_locatable
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.manifold import TSNE
from scipy.stats import ttest_ind
import scipy.stats as stats
from skbio.stats.distance import mantel
from factor_analyzer import FactorAnalyzer
from factor_analyzer.factor_analyzer import calculate_kmo, calculate_bartlett_sphericity
import factor_analyzer.factor_analyzer as fa_module
warnings.filterwarnings('ignore', message='.*Moore-Penrose.*')
warnings.filterwarnings('ignore', message='.*invalid value encountered in log.*')
warnings.filterwarnings('ignore', message=".*'force_all_finite' was renamed.*")
os.environ['HF_HOME'] = '/Users/devon7y/.cache/huggingface'
os.environ['HF_DATASETS_CACHE'] = '/Users/devon7y/.cache/huggingface'
with open(os.path.expanduser('~/.cache/huggingface/token'), 'r') as f:
os.environ['HF_TOKEN'] = f.read().strip()
plt.rcParams.update({
'font.size': 13,
'axes.titlesize': 15,
'axes.labelsize': 13,
'xtick.labelsize': 12,
'ytick.labelsize': 12,
'legend.fontsize': 11,
'figure.titlesize': 20,
})
sns.set_context("notebook", font_scale=1.25)
COMPARISON_SUBPLOT_SPACING = 1
MODEL_NAMES = ["dwulff/mpnet-personality",]
MODEL_SIZE_OVERRIDES = {
"dwulff/mpnet-personality": "mpnet",
}
SCALE_NAMES = ["DASS"]
RUN_ALL_SCALES = True
# SCALE_NAMES = [
# "Big5FM", "OSRI", "NIS", "RIASEC", "MACHIV", "HSNDD",
# "ECR", "16PF", "RSE", "FBPS", "DASS", "NPAS",
# "HEXACO", "c", "SD3", "GSE", "CFCS", "EQSQ",
# "RWAS", "MFQ", "TMA", "FTI", "DGS", "NFC",
# "EPQ", "AMBI", "IRI", "GCB", "CIS", "ERRI",
# "BDI", "BAI", "HSQ", "KIMS", "LLMD12", "431PTQ"]
# All 36 scales ordered by participant count
PREGENERATED_WORD_EMBEDDINGS = {}
N_FACTORS = None # None = auto via parallel analysis
APPLY_REVERSE_SCORING_EMBEDDINGS = False # Guenole et al.'s atomic-reversed encoding
ROTATION_METHOD = 'oblimin'
# OBLIQUE rotations (factors can correlate):
# - 'promax': Promax rotation (power parameter defaults to 4)
# - 'oblimin': Direct oblimin rotation (gamma parameter defaults to 0)
# - 'quartimin': Quartimin rotation (minimizes cross-loadings)
# - 'geomin_obl': Oblique geomin rotation (delta parameter defaults to 0.01)
#
# ORTHOGONAL rotations (factors remain uncorrelated):
# - 'varimax': Varimax rotation (maximizes variance of squared loadings)
# - 'quartimax': Quartimax rotation (minimizes variables' factor complexity)
# - 'equamax': Equamax rotation (kappa parameter defaults to 0)
# - 'oblimax': Oblimax rotation
# - 'geomin_ort': Orthogonal geomin rotation (delta parameter defaults to 0.01)
EXTRACTION_METHOD = 'minres'
# - 'minres' or 'uls': Minimum residual / Unweighted Least Squares (fast, stable, default)
# - 'ml' or 'mle': Maximum Likelihood Extraction (slower, assumes multivariate normality)
# - 'principal': Principal factor analysis (uses SVD on raw data, requires full dataset)
EIGEN_CRITERIA = 'parallel' # 'parallel' or 'eigen1'
PARALLEL_ITER = 100
RANDOM_STATE = 42
ENABLE_FACTOR_NAMING = True
ENABLE_METHOD_3 = False # Greedy token prediction for factor naming (experimental, may produce low-quality names)
# Optional manual ordering for extracted factors in EMBEDDING plots.
# Leave empty [] to use existing/default ordering logic.
# You can use either extracted names (e.g., "Factor1") or display labels
# (e.g., LLM-generated factor names).
PLOT_EXTRACTED_FACTOR_ORDER = ["Creativity", "Order and Preparedness", "Social Dynamics", "Empathy", "Anxiety and Mood Instability", "Conceptual Thinking"]
# Optional manual ordering for extracted factors in EMPIRICAL (human response)
# plots. Leave empty [] to use existing/default ordering logic.
PLOT_EXTRACTED_FACTOR_ORDER_EMPIRICAL = ["Openness to Experience", "Conscientiousness", "Extraversion", "Agreeableness", "Neuroticism"]
def get_model_size(model_name):
"""Return model label used for cache filenames and reporting."""
return MODEL_SIZE_OVERRIDES.get(model_name, model_name.split('-')[-1])
def load_sentence_transformer_model(model_name, device):
"""
Load a SentenceTransformer from local HF snapshots when available.
If no snapshot is present, load by repo id (downloads once, then caches).
"""
model_cache_name = model_name.replace('/', '--')
snapshots_dir = f"/Users/devon7y/.cache/huggingface/models--{model_cache_name}/snapshots"
snapshot_dirs = glob.glob(f"{snapshots_dir}/*")
if snapshot_dirs:
snapshot_path = snapshot_dirs[0]
print(f" Loading from local snapshot: {snapshot_path}")
return SentenceTransformer(snapshot_path, device=device)
print(f" No local snapshot found for {model_name}")
print(" Loading from Hugging Face repo ID (downloads once, then caches locally)...")
return SentenceTransformer(model_name, device=device)
np.random.seed(RANDOM_STATE)
torch.manual_seed(RANDOM_STATE)
print("✓ Configuration loaded")
def apply_atomic_reversed(embeddings, scoring):
"""Apply atomic-reversed encoding"""
scoring_array = np.array(scoring).reshape(-1, 1)
embeddings_signed = embeddings * scoring_array
norms = np.linalg.norm(embeddings_signed, axis=1)
zero_norm_items = np.where(norms == 0)[0]
if len(zero_norm_items) > 0:
print(f" WARNING: {len(zero_norm_items)} items have zero norm after signing")
for idx in zero_norm_items:
embeddings_signed[idx] = embeddings[idx]
embeddings_normalized = embeddings_signed / np.linalg.norm(embeddings_signed, axis=1, keepdims=True)
return embeddings_normalized
def compute_parallel_analysis(corr_matrix, n_iter=100, percentile=95, random_state=42, n_obs=None):
"""Parallel analysis for factor retention"""
np.random.seed(random_state)
n_items = corr_matrix.shape[0]
obs_eigenvalues = np.linalg.eigvalsh(corr_matrix)
obs_eigenvalues = np.sort(obs_eigenvalues)[::-1]
random_eigenvalues = []
if n_obs is None:
n_obs = n_items * 10
for _ in range(n_iter):
random_data = np.random.randn(n_obs, n_items)
random_corr = np.corrcoef(random_data, rowvar=False)
eigs = np.linalg.eigvalsh(random_corr)
eigs = np.sort(eigs)[::-1]
random_eigenvalues.append(eigs)
random_eigenvalues = np.array(random_eigenvalues)
percentiles = np.percentile(random_eigenvalues, percentile, axis=0)
n_factors = np.sum(obs_eigenvalues > percentiles)
return n_factors, obs_eigenvalues, percentiles
def compute_daal(loadings_df, theoretical_factors):
"""Compute DAAL (Dominant Average Absolute Loading)"""
theoretical_unique = sorted(set(theoretical_factors))
extracted_factors = loadings_df.columns
daal_matrix = []
for ext_factor in extracted_factors:
row = []
for theo_factor in theoretical_unique:
mask = [f == theo_factor for f in theoretical_factors]
loadings_subset = loadings_df.loc[mask, ext_factor]
daal_value = loadings_subset.abs().mean()
row.append(daal_value)
daal_matrix.append(row)
daal_df = pd.DataFrame(daal_matrix, index=extracted_factors, columns=theoretical_unique)
return daal_df
def compute_tucker_congruence(factor_loadings, reference_loadings):
"""Compute Tucker congruence coefficient (phi)"""
numerator = np.sum(factor_loadings * reference_loadings)
denom = np.sqrt(np.sum(factor_loadings**2)) * np.sqrt(np.sum(reference_loadings**2))
return numerator / denom if denom != 0 else 0.0
def create_theoretical_indicators(theoretical_factors, codes):
"""Create indicator matrix for theoretical factors"""
unique_factors = sorted(set(theoretical_factors))
indicators = []
for factor in unique_factors:
indicator = [1.0 if f == factor else 0.0 for f in theoretical_factors]
indicators.append(indicator)
indicators_df = pd.DataFrame(np.array(indicators).T, columns=unique_factors, index=codes)
return indicators_df
def assign_items_to_extracted_factors(loadings_df, use_abs=True):
"""Assign each item to the extracted factor with the largest loading."""
item_to_factor = {}
for item_code in loadings_df.index:
loadings = loadings_df.loc[item_code].abs() if use_abs else loadings_df.loc[item_code]
item_to_factor[item_code] = loadings.idxmax()
return item_to_factor
def build_unique_extracted_factor_label_map(extracted_factors, tucker_best=None):
"""
Build display labels for extracted factors.
Each theoretical label is used at most once. If multiple extracted factors
map to the same theoretical factor, only the best-congruent one keeps that
label; the rest keep their original names (e.g., Factor2).
"""
extracted_factors = list(extracted_factors)
label_map = {factor: factor for factor in extracted_factors}
if tucker_best is None or not isinstance(tucker_best, pd.DataFrame):
return label_map
required_cols = {'extracted_factor', 'best_match'}
if not required_cols.issubset(tucker_best.columns):
return label_map
candidates = tucker_best[tucker_best['extracted_factor'].isin(extracted_factors)].copy()
if candidates.empty:
return label_map
if 'tucker_phi' in candidates.columns:
candidates['tucker_phi'] = pd.to_numeric(candidates['tucker_phi'], errors='coerce')
else:
candidates['tucker_phi'] = np.nan
factor_order = {factor: i for i, factor in enumerate(extracted_factors)}
candidates['_factor_order'] = candidates['extracted_factor'].map(factor_order).fillna(len(factor_order)).astype(int)
candidates = candidates.sort_values(
by=['best_match', 'tucker_phi', '_factor_order'],
ascending=[True, False, True],
kind='mergesort'
)
winners = candidates.drop_duplicates(subset=['best_match'], keep='first')
for _, row in winners.iterrows():
best_match = row['best_match']
if pd.isna(best_match):
continue
label = str(best_match).strip()
if not label:
continue
label_map[row['extracted_factor']] = label
return label_map
def get_extracted_factor_display_labels(extracted_factors, tucker_best=None):
"""Return ordered display labels and factor->label mapping."""
extracted_factors = list(extracted_factors)
label_map = build_unique_extracted_factor_label_map(extracted_factors, tucker_best)
labels = [label_map.get(factor, factor) for factor in extracted_factors]
return labels, label_map
def get_embedding_factor_display_labels(extracted_factors, model_size):
"""
Return display labels for embedding factors.
- ENABLE_FACTOR_NAMING=True: use LLM-generated names when available.
- ENABLE_FACTOR_NAMING=False: keep original extracted names (Factor1, Factor2, ...).
"""
extracted_factors = list(extracted_factors)
label_map = {factor: factor for factor in extracted_factors}
if ENABLE_FACTOR_NAMING:
try:
model_mapping = factor_name_mappings_nn.get(model_size, {})
except NameError:
model_mapping = {}
for factor in extracted_factors:
label_map[factor] = model_mapping.get(factor, factor)
labels = [label_map[factor] for factor in extracted_factors]
return labels, label_map
def apply_manual_extracted_factor_order(factor_names, display_name_map=None, manual_order=None):
"""
Reorder extracted factors based on a provided manual order list.
Matches each manual entry against either raw extracted factor names
(e.g., "Factor1") or display names (e.g., LLM labels). Unmatched factors
keep their original order after matched factors.
"""
factors = list(factor_names)
manual_order = manual_order or []
if not manual_order:
return factors
display_name_map = display_name_map or {}
key_to_factor = {}
for factor in factors:
raw_key = str(factor).strip().lower()
disp_key = str(display_name_map.get(factor, factor)).strip().lower()
if raw_key:
key_to_factor.setdefault(raw_key, factor)
if disp_key:
key_to_factor.setdefault(disp_key, factor)
ordered = []
used = set()
for entry in manual_order:
key = str(entry).strip().lower()
factor = key_to_factor.get(key)
if factor is not None and factor not in used:
ordered.append(factor)
used.add(factor)
for factor in factors:
if factor not in used:
ordered.append(factor)
return ordered
print("✓ Helper functions defined")
def regularize_correlation_matrix(corr_matrix, alpha=1e-6):
"""Add regularization to correlation matrix."""
is_df = isinstance(corr_matrix, pd.DataFrame)
corr_array = corr_matrix.values.copy() if is_df else corr_matrix.copy()
n = corr_array.shape[0]
regularized = corr_array + alpha * np.eye(n)
diag = np.sqrt(np.diag(regularized))
regularized = regularized / diag[:, None] / diag[None, :]
if is_df:
return pd.DataFrame(regularized, index=corr_matrix.index, columns=corr_matrix.columns)
return regularized
def safe_calculate_kmo(corr_matrix, alpha=1e-6):
"""KMO with auto-regularization."""
try:
return fa_module._original_calculate_kmo(corr_matrix)
except (np.linalg.LinAlgError, AssertionError):
print(f" ⚠️ Singular matrix detected, applying regularization (alpha={alpha})...")
return fa_module._original_calculate_kmo(regularize_correlation_matrix(corr_matrix, alpha))
def safe_calculate_bartlett(corr_matrix, alpha=1e-6):
"""Bartlett with auto-regularization."""
try:
return fa_module._original_calculate_bartlett(corr_matrix)
except (np.linalg.LinAlgError, AssertionError):
print(f" ⚠️ Singular matrix detected, applying regularization (alpha={alpha})...")
return fa_module._original_calculate_bartlett(regularize_correlation_matrix(corr_matrix, alpha))
if not hasattr(fa_module, '_original_calculate_kmo'):
importlib.reload(fa_module)
fa_module._original_calculate_kmo = fa_module.calculate_kmo
fa_module._original_calculate_bartlett = fa_module.calculate_bartlett_sphericity
fa_module.calculate_kmo = safe_calculate_kmo
fa_module.calculate_bartlett_sphericity = safe_calculate_bartlett
print("✓ Safe KMO and Bartlett calculation functions installed")
env_scale_index = os.environ.get("SFA_SCALE_INDEX")
if env_scale_index is not None:
try:
CURRENT_SCALE_INDEX = int(env_scale_index)
except ValueError as exc:
raise ValueError(f"SFA_SCALE_INDEX must be an integer, got: {env_scale_index}") from exc
else:
CURRENT_SCALE_INDEX = 0
if CURRENT_SCALE_INDEX >= len(SCALE_NAMES):
raise ValueError(f"CURRENT_SCALE_INDEX ({CURRENT_SCALE_INDEX}) is out of range. SCALE_NAMES has {len(SCALE_NAMES)} scales.")
SCALE_NAME = SCALE_NAMES[CURRENT_SCALE_INDEX]
if RUN_ALL_SCALES and CURRENT_SCALE_INDEX == 0 and len(SCALE_NAMES) > 1 and env_scale_index is None:
print(f"Batch mode enabled: processing all {len(SCALE_NAMES)} scales in sequence")
print(f"{'='*80}")
print(f"PROCESSING SCALE: {SCALE_NAME}")
print(f" (Scale {CURRENT_SCALE_INDEX + 1} of {len(SCALE_NAMES)})")
print(f"{'='*80}\n")
PREGENERATED_SCALE_EMBEDDINGS = {}
SCALE_CSV_PATH = f'scale_items/{SCALE_NAME}_items.csv'
EMPIRICAL_DATA_PATH = f"scale_responses/{SCALE_NAME}_data.csv"
SAVE_DIR = f'results/{SCALE_NAME}'
os.makedirs(SAVE_DIR, exist_ok=True)
SCALE_NAME_DISPLAY = Path(SCALE_CSV_PATH).stem.replace('_items', '')
log_file_path = f"{SAVE_DIR}/{SCALE_NAME}_analysis_log.txt"
class Logger:
def __init__(self, filename):
self.terminal = sys.stdout
self.log = open(filename, 'w', encoding='utf-8')
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
self.terminal.flush()
self.log.flush()
def close(self):
self.log.close()
logger = Logger(log_file_path)
sys.stdout = logger
print(f"Loading {SCALE_CSV_PATH}...")
scale = pd.read_csv(SCALE_CSV_PATH)
print(f"Loaded {len(scale)} items")
required = ['code', 'item', 'factor']
missing = [c for c in required if c not in scale.columns]
if missing:
raise ValueError(f"Missing required columns: {missing}")
if 'scoring' not in scale.columns:
print("⚠ WARNING: 'scoring' column missing - defaulting to +1")
scale['scoring'] = 1
print(f"\nScoring: {(scale['scoring']==1).sum()} normal, {(scale['scoring']==-1).sum()} reverse")
print(f"Factors: {scale['factor'].nunique()} unique")
print(scale['factor'].value_counts().sort_index())
codes = scale['code'].tolist()
items = scale['item'].tolist()
factors = scale['factor'].tolist()
scoring = scale['scoring'].tolist()
print(f"\n✓ Data validated: {len(items)} items, {len(set(factors))} factors")
empirical_data = None
if EMPIRICAL_DATA_PATH is not None:
print(f"\n{'='*70}")
print("Loading empirical response data...")
print(f"{'='*70}")
try:
with open(EMPIRICAL_DATA_PATH, 'r') as f:
first_line = f.readline()
tab_count = first_line.count('\t')
comma_count = first_line.count(',')
if tab_count > comma_count:
delimiter = '\t'
else:
delimiter = ','
empirical_df = pd.read_csv(EMPIRICAL_DATA_PATH, sep=delimiter)
print(f"✓ Loaded from: {EMPIRICAL_DATA_PATH}")
print(f" Shape: {empirical_df.shape} (participants × items)")
print(f" Participants: {len(empirical_df):,}")
print(f" Items: {len(empirical_df.columns)}")
data_codes = list(empirical_df.columns)
if data_codes != codes:
print(f"\n⚠ WARNING: Column mismatch detected!")
print(f" Scale definition codes: {codes[:5]}...")
print(f" Data columns: {data_codes[:5]}...")
if set(data_codes) == set(codes):
print(f" → Reordering columns to match scale definition...")
empirical_df = empirical_df[codes]
print(f" ✓ Columns reordered successfully")
else:
missing = set(codes) - set(data_codes)
extra = set(data_codes) - set(codes)
print(f" → Missing codes: {missing}")
print(f" → Extra codes: {extra}")
raise ValueError("Column names do not match scale item codes")
else:
print(f" ✓ Column names match scale item codes")
empirical_data = empirical_df.values.astype(float)
min_val = empirical_data.min()
max_val = empirical_data.max()
print(f"\n Response range: [{min_val:.0f}, {max_val:.0f}]")
print(f"\n Sample statistics:")
print(f" Mean response: {empirical_data.mean():.2f}")
print(f" SD response: {empirical_data.std():.2f}")
print(f" Missing values: {np.isnan(empirical_data).sum():,}")
print(f"\n✓ Empirical data ready for analysis")
except FileNotFoundError:
print(f"\n✗ ERROR: File not found: {EMPIRICAL_DATA_PATH}")
print(" Empirical analysis will be skipped.")
empirical_data = None
except Exception as e:
print(f"\n✗ ERROR loading empirical data:")
print(f" {type(e).__name__}: {str(e)}")
print(" Empirical analysis will be skipped.")
empirical_data = None
else:
print(f"\n{'='*70}")
print("Empirical data path not specified - skipping empirical analysis")
print(f"{'='*70}")
if torch.cuda.is_available():
device = 'cuda'
print(f"✓ CUDA: {torch.cuda.get_device_name(0)}")
elif torch.backends.mps.is_available():
device = 'mps'
print("✓ Apple MPS")
else:
device = 'cpu'
print("Using CPU")
all_embeddings = {}
model_sizes = []
for model_name in MODEL_NAMES:
model_size = get_model_size(model_name)
model_sizes.append(model_size)
print(f"\nModel: {model_name} ({model_size})")
if model_size in PREGENERATED_SCALE_EMBEDDINGS:
scale_emb_path = PREGENERATED_SCALE_EMBEDDINGS[model_size]
if os.path.exists(scale_emb_path):
try:
data = np.load(scale_emb_path, allow_pickle=True)
embeddings = None
for key in ['embeddings', 'scale_embeddings', 'vectors', 'arr_0']:
if key in data:
embeddings = data[key]
print(f" ✓ Loaded from key '{key}': {embeddings.shape}")
break
if embeddings is None:
print(f" ⚠ Warning: No valid embedding key found in {scale_emb_path}")
print(f" Available keys: {list(data.keys())}")
print(f" Falling back to cache or generation...")
else:
if embeddings.shape[0] != len(items):
print(f" ⚠ WARNING: Embedding count ({embeddings.shape[0]}) != item count ({len(items)})")
print(f" Falling back to cache or generation...")
else:
all_embeddings[model_size] = embeddings
continue
except Exception as e:
print(f" ⚠ Warning: Error loading pregenerated embeddings:")
print(f" {type(e).__name__}: {str(e)}")
print(f" Falling back to cache or generation...")
else:
print(f" ⚠ Pregenerated path specified but file not found: {scale_emb_path}")
print(f" Falling back to cache or generation...")
scale_cache_path = f"embeddings/{SCALE_NAME}_items_{model_size}.npz"
legacy_cache_path = f"embeddings/scale_items_{model_size}.npz"
cache_candidates = [scale_cache_path]
if legacy_cache_path not in cache_candidates:
cache_candidates.append(legacy_cache_path)
loaded_from_cache = False
for save_path in cache_candidates:
if not os.path.exists(save_path):
continue
print(f" Loading from cache: {save_path}...")
try:
data = np.load(save_path, allow_pickle=True)
embeddings = data['embeddings']
if embeddings.shape[0] != len(items):
print(f" ⚠ Cached embedding count ({embeddings.shape[0]}) != item count ({len(items)})")
print(f" Skipping cache file: {save_path}")
continue
if 'codes' in data:
cached_codes = data['codes'].tolist()
if cached_codes != codes:
print(f" ⚠ Cached codes do not match current scale codes")
print(f" Skipping cache file: {save_path}")
continue
print(f" ✓ Loaded: {embeddings.shape}")
all_embeddings[model_size] = embeddings
loaded_from_cache = True
break
except Exception as e:
print(f" ⚠ Warning: Failed to load cache file {save_path}")
print(f" {type(e).__name__}: {str(e)}")
if loaded_from_cache:
continue
print(f" Generating embeddings...")
model = load_sentence_transformer_model(model_name=model_name, device=device)
embeddings = model.encode(items, show_progress_bar=True, batch_size=21,
convert_to_numpy=True, normalize_embeddings=False)
print(f" ✓ Generated: {embeddings.shape}")
all_embeddings[model_size] = embeddings
os.makedirs("embeddings", exist_ok=True)
np.savez(scale_cache_path, embeddings=embeddings, codes=codes, items=items)
print(f" ✓ Saved to {scale_cache_path}")
print(f"\n✓ All embeddings ready: {list(all_embeddings.keys())}")
print(f"\n{'='*70}")
print("Sample Embeddings (First 3 Items)")
print(f"{'='*70}")
for model_size in model_sizes:
embeddings = all_embeddings[model_size]
print(f"\nModel: {model_size}")
for i in range(min(3, len(items))):
print(f"\n Item {i+1}: {codes[i]}")
print(f" Text: {items[i][:60]}{'...' if len(items[i]) > 60 else ''}")
print(f" Embedding shape: {embeddings[i].shape}")
print(f" First 10 values: {embeddings[i][:10]}")
print(f" L2 norm: {np.linalg.norm(embeddings[i]):.4f}")
def run_pfa_for_model(model_size, embeddings, codes, items, factors, scoring,
n_factors=None, rotation='promax', extraction_method='minres',
eigen_criteria='parallel', parallel_iter=100, random_state=42,
save_dir='results'):
"""
Run complete Semantic Factor Analysis pipeline for one model.
Args:
model_size: str, e.g., "4B"
embeddings: (n_items, dim) array
codes: list of item codes
items: list of item texts
factors: list of theoretical factor labels
scoring: list of +1/-1 scoring directions
n_factors: int or None (None = auto via parallel analysis)
rotation: str, rotation method (e.g., 'promax', 'oblimin', 'varimax')
extraction_method: str, extraction method (e.g., 'minres', 'ml', 'principal')
eigen_criteria: 'parallel' or 'eigen1'
parallel_iter: int, iterations for parallel analysis
random_state: int, for reproducibility
save_dir: directory to save results
Returns:
results: dict with all results
"""
print(f"SEMANTIC FACTOR ANALYSIS: {model_size}")
results = {'model_size': model_size}
if APPLY_REVERSE_SCORING_EMBEDDINGS:
print("\n[1/7] Applying atomic-reversed encoding...")
embeddings_ar = apply_atomic_reversed(embeddings, scoring)
print(f" ✓ Shape: {embeddings_ar.shape}")
else:
print("\n[1/7] Normalizing embeddings (reverse scoring disabled)...")
# Just normalize without applying scoring direction
embeddings_ar = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
print(f" ✓ Shape: {embeddings_ar.shape}")
print(f" ⚠ Reverse scoring disabled - all items treated as normally scored")
print("\n[2/7] Computing cosine similarity matrix...")
sim_matrix = cosine_similarity(embeddings_ar)
print(f" ✓ Shape: {sim_matrix.shape}")
results['similarity_matrix'] = sim_matrix
print("\n[3/7] Computing KMO and Bartlett test...")
kmo_per_item, kmo_total = calculate_kmo(sim_matrix)
print(f" ✓ KMO overall: {kmo_total:.3f}")
if kmo_total < 0.5:
print(" ⚠ WARNING: KMO < 0.5 (unacceptable)")
elif kmo_total < 0.6:
print(" ⚠ WARNING: KMO < 0.6 (poor)")
elif kmo_total < 0.7:
print(" KMO is mediocre")
elif kmo_total < 0.8:
print(" KMO is middling")
elif kmo_total < 0.9:
print(" KMO is meritorious")
else:
print(" KMO is marvelous")
chi_square, p_value = calculate_bartlett_sphericity(sim_matrix)
print(f" ✓ Bartlett: χ²={chi_square:.2f}, p={p_value:.4e}")
if p_value > 0.05:
print(" ⚠ WARNING: Not significant (p > 0.05)")
else:
print(" ✓ Significant (p < 0.05)")
results['kmo_total'] = kmo_total
results['kmo_per_item'] = kmo_per_item
results['bartlett_chi2'] = chi_square
results['bartlett_p'] = p_value
print("\n[4/7] Determining number of factors...")
eigs = np.linalg.eigvalsh(sim_matrix)
eigs = np.sort(eigs)[::-1]
results['observed_eigenvalues'] = eigs
if n_factors is None:
if eigen_criteria == 'parallel':
print(f" Running parallel analysis ({parallel_iter} iterations)...")
n_factors_auto, obs_eigs, percentile_eigs = compute_parallel_analysis(
sim_matrix, n_iter=parallel_iter, random_state=random_state
)
print(f" ✓ Suggested {n_factors_auto} factors")
n_factors = max(1, n_factors_auto)
results['percentile_eigenvalues'] = percentile_eigs
else:
n_factors = np.sum(eigs > 1)
print(f" ✓ Kaiser rule (eigen>1): {n_factors} factors")
print(f" ✓ Extracting {n_factors} factors with {rotation} rotation")
results['n_factors'] = n_factors
print("\n[5/7] Running Exploratory Factor Analysis...")
fa = FactorAnalyzer(
n_factors=n_factors,
rotation=rotation,
method=extraction_method,
is_corr_matrix=True,
rotation_kwargs={'normalize': True} if rotation in ['promax', 'oblimin'] else {}
)
fa.fit(sim_matrix)
print(" ✓ EFA complete")
loadings = fa.loadings_
communalities = fa.get_communalities()
uniquenesses = fa.get_uniquenesses()
variance = fa.get_factor_variance()
factor_names = [f"Factor{i+1}" for i in range(n_factors)]
loadings_df = pd.DataFrame(loadings, index=codes, columns=factor_names)
print(f" Loadings shape: {loadings.shape}")
print(f" Variance explained (cumulative): {variance[2][-1]:.1%}")
variance_df = pd.DataFrame(variance, index=['SS Loadings', 'Proportion', 'Cumulative'])
communalities_df = pd.DataFrame({
'communality': communalities,
'uniqueness': uniquenesses
}, index=codes)
results['loadings'] = loadings_df
results['variance'] = variance
results['communalities'] = communalities
results['uniquenesses'] = uniquenesses
print("\n[6/7] Computing DAAL...")
daal_df = compute_daal(loadings_df, factors)
print(f" ✓ DAAL matrix: {daal_df.shape}")
assignments = []
for ext_factor in daal_df.index:
best_theo = daal_df.loc[ext_factor].idxmax()
best_daal = daal_df.loc[ext_factor, best_theo]
assignments.append({
'extracted_factor': ext_factor,
'assigned_to': best_theo,
'daal': best_daal
})
assignments_df = pd.DataFrame(assignments)
print("\n Factor assignments (DAAL):")
for _, row in assignments_df.iterrows():
print(f" {row['extracted_factor']} → {row['assigned_to']} (DAAL={row['daal']:.3f})")
results['daal'] = daal_df
results['daal_assignments'] = assignments_df
print("\n[7/7] Computing Tucker congruence...")
theoretical_indicators = create_theoretical_indicators(factors, codes)
tucker_matrix = []
for ext_factor in factor_names:
row = []
for theo_factor in theoretical_indicators.columns:
phi = compute_tucker_congruence(
loadings_df[ext_factor].values,
theoretical_indicators[theo_factor].values
)
row.append(phi)
tucker_matrix.append(row)
tucker_df = pd.DataFrame(
tucker_matrix,
index=factor_names,
columns=theoretical_indicators.columns
)
print(f" ✓ Tucker matrix: {tucker_df.shape}")
print("\n Interpretation guide:")
print(" φ ≥ .95: Excellent agreement")
print(" φ ≥ .85: Fair agreement")
print(" φ < .85: Poor agreement")
tucker_best = []
for ext_factor in tucker_df.index:
best_theo = tucker_df.loc[ext_factor].idxmax()
best_phi = tucker_df.loc[ext_factor, best_theo]
tucker_best.append({
'extracted_factor': ext_factor,
'best_match': best_theo,
'tucker_phi': best_phi
})
tucker_best_df = pd.DataFrame(tucker_best)
print("\n Best matches (Tucker φ):")
for _, row in tucker_best_df.iterrows():
print(f" {row['extracted_factor']} ↔ {row['best_match']} (φ={row['tucker_phi']:.3f})")
results['tucker'] = tucker_df
results['tucker_best'] = tucker_best_df
diagnostics = {
'model': model_size,
'n_items': len(codes),
'n_factors_extracted': n_factors,
'rotation': rotation,
}
diagnostics['kmo'] = kmo_total
diagnostics['bartlett_p'] = p_value
diagnostics['variance_explained'] = variance[2][-1]
diagnostics_df = pd.DataFrame([diagnostics])
results['diagnostics'] = diagnostics_df
print(f"\n{'='*70}")
print(f"✓ SFA COMPLETE FOR {model_size}")
print('='*70)
return results
def run_efa_on_data(data_label, response_data, codes, items, factors, scoring,
n_factors=None, rotation='promax', extraction_method='minres',
eigen_criteria='parallel', parallel_iter=100, random_state=42,
save_dir='results'):
"""
Run traditional Exploratory Factor Analysis on raw Likert scale response data.
This function follows traditional factor analysis conventions:
- Uses Pearson correlation matrix instead of cosine similarity
- Applies reverse scoring but does NOT normalize to unit vectors
- Otherwise identical pipeline to run_pfa_for_model()
Parameters:
-----------
data_label : str
Label for this dataset (e.g., "Empirical", "DASS_Study1")
response_data : ndarray of shape (n_participants, n_items)
Raw Likert scale responses (participants × items)
codes : list of str
Item codes (e.g., ["S1", "A2", "D3"])
items : list of str
Full item text
factors : list of str
Theoretical factor labels
scoring : list of int
+1 for normal items, -1 for reverse-scored
n_factors : int or None
Number of factors to extract (None = auto via parallel analysis)
rotation : str
Rotation method ('promax', 'oblimin', 'varimax', etc.)
extraction_method : str
'minres', 'ml', or 'principal'
eigen_criteria : str
'parallel' or 'eigen1'
parallel_iter : int
Iterations for parallel analysis
random_state : int
Random seed for reproducibility
save_dir : str
Output directory
Returns:
--------
dict : Analysis results including correlation matrix, loadings, diagnostics, etc.
"""
print(f"\n{'='*70}")
print(f"TRADITIONAL EFA - {data_label}")
print(f"{'='*70}")
print(f"Data: {response_data.shape[0]:,} participants × {response_data.shape[1]} items")
print(f"Rotation: {rotation}")
print(f"Extraction: {extraction_method}")
print(f"\n[1/7] Applying reverse scoring...")
response_scored = response_data.copy()
for i, score_dir in enumerate(scoring):