Datasets:
Tasks:
Feature Extraction
Formats:
parquet
Languages:
Multiple languages
Size:
100K - 1M
ArXiv:
License:
| # ruff: noqa: T201 # CLI build-script report payload (CLAUDE.md whitelist) | |
| """Build NuBerea/concept-analysis — consolidated analytical layer for concept topology. | |
| Absorbs all of NuBerea/concept-trajectories and migrates three analytical configs | |
| from NuBerea/concept-graph (community_candidate, community_membership, concept_centroids). | |
| Boundary principle: | |
| concept-graph = topology (span_node, span_edge, concept_node, concept_span_edge, ...) | |
| concept-analysis = derived outputs (centroids, communities, trajectories, drift) | |
| Output configs (20 total, writing 22 parquet dirs — pseu builds write deut+pseu each): | |
| concept_verse_edge — 28,909 rows; concept×verse, LXX+NT strata, shlm-grc-en 768-dim | |
| concept_trajectory — 112 rows; concept×stratum centroids, LXX+NT | |
| concept_verse_edge_sp — 59,478 rows; concept×verse, LXX+NT+Vulgate, SPhilBerta 768-dim | |
| concept_trajectory_sp — 190 rows; concept×stratum centroids, LXX+NT+Vulgate | |
| concept_verse_edge_bt — 59,478 rows; concept_verse_edge_sp + bt_layer + plate_segment (T8) | |
| concept_trajectory_bt — ~960 rows; concept×bt_layer centroids (T8, match_grain=pericope) | |
| concept_verse_edge_deut — ~5,857 rows; Deuterocanon verses, nearest-centroid assignment | |
| concept_verse_edge_pseu — ~15,043 rows; Pseudepigrapha verses, nearest-centroid assignment | |
| concept_trajectory_deut — per-concept centroids for Deuterocanon stratum | |
| concept_trajectory_pseu — per-concept centroids for Pseudepigrapha stratum | |
| concept_drift — 78 rows; Schlattmann&Vogl 2024 drift metrics per concept×transition | |
| concept_drift_itp — 78 rows; PSEU-extended drift (5 pairs: lxx→deut/pseu, deut/pseu→nt, deut→pseu) | |
| concept_drift_hamilton — 5,023 rows; Hamilton/CADE word2vec drift per lemma (3 languages) | |
| community_candidate — 55 rows; community summaries (from concept-graph) | |
| community_membership — 2,412 rows; pericope→community assignments (from concept-graph) | |
| concept_centroids — 156 rows; L1+L2 bi_encoder_v1 384-dim centroids (from concept-graph) | |
| concept_aliases — 567 rows; TF-IDF English term → bt1_xxx concept_id list mappings | |
| concept_verse_edge_patr — ~40K rows; patristic GRC segments, nearest-centroid assignment | |
| concept_verse_edge_philo — ~7.9K rows; Philo of Alexandria GRC segments, nearest-centroid | |
| concept_verse_edge_josephus — ~12.7K rows; Josephus GRC segments, nearest-centroid | |
| concept_verse_edge_targum — ~28K rows; Targum English translations, nearest-centroid | |
| concept_verse_edge_talmud — ~200K rows; Mishnah+Tosefta English translations, nearest-centroid | |
| Source data (local build dirs + HF for HF-native configs): | |
| huggingface/candidates/build/concept-trajectories/data/ | |
| huggingface/candidates/build/concept-graph/data/ | |
| huggingface/candidates/build/concept-trajectories/data/concept_drift_analysis.csv | |
| concept_aliases: HF-native — NuBerea/AI-models bi_encoder_v1 + question_bin_assignment.json | |
| + NuBerea/concept-graph concept_node centroids | |
| concept_verse_edge_bt / concept_trajectory_bt: T8 — read NuBerea/pericope-genealogy | |
| composition_dag (local until genealogy HF upload); promote concept-analysis to T8 for | |
| bt-indexed configs only. | |
| Usage: | |
| python scripts/build.py # build all configs | |
| python scripts/build.py --config X # build only config X | |
| For HF-native reproducibility of the trajectory configs, see verify.py in this directory. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import pathlib | |
| import sys | |
| import pandas as pd | |
| BUILD = pathlib.Path("huggingface/candidates/build") | |
| OUT = BUILD / "concept-analysis/data" | |
| # Make hf_registry importable | |
| _THIS = pathlib.Path(__file__).resolve() | |
| _CANDIDATES = _THIS.parents[2] | |
| if str(_CANDIDATES) not in sys.path: | |
| sys.path.insert(0, str(_CANDIDATES)) | |
| from hf_registry import load_hf_or_local | |
| def _parquet_out(config: str) -> pathlib.Path: | |
| p = OUT / config | |
| p.mkdir(parents=True, exist_ok=True) | |
| return p / "train-00000-of-00001.parquet" | |
| def import_trajectory_config(name: str) -> None: | |
| """Import a trajectory config from NuBerea/concept-trajectories (HF-native, local fallback).""" | |
| ds = load_hf_or_local("NuBerea/concept-analysis", name) | |
| df = ds.to_pandas() | |
| dst = _parquet_out(name) | |
| df.to_parquet(dst, index=False) | |
| print(f" {name}: {len(df):,} rows, {len(df.columns)} cols — imported from NuBerea/concept-trajectories") | |
| def build_concept_drift() -> None: | |
| """Compute drift inline from concept_trajectory_sp + concept_verse_edge_sp (HF-native).""" | |
| sys.path.insert(0, str(_THIS.parent)) | |
| from analyze_concept_drift import compute_drift_dataframe | |
| traj = load_hf_or_local("NuBerea/concept-analysis", "concept_trajectory_sp").to_pandas() | |
| cve = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_sp").to_pandas() | |
| df = compute_drift_dataframe(traj, cve) | |
| dst = _parquet_out("concept_drift") | |
| df.to_parquet(dst, index=False) | |
| print(f" concept_drift: {len(df)} rows, {len(df.columns)} cols — computed inline (HF-native)") | |
| def import_community_config(name: str) -> None: | |
| """Import a community config from NuBerea/concept-graph (HF-native, local fallback).""" | |
| ds = load_hf_or_local("NuBerea/concept-graph", name) | |
| df = ds.to_pandas() | |
| dst = _parquet_out(name) | |
| df.to_parquet(dst, index=False) | |
| print(f" {name}: {len(df):,} rows, {len(df.columns)} cols — imported from NuBerea/concept-graph") | |
| def build_concept_centroids() -> None: | |
| """Build concept_centroids from NuBerea/concept-graph concept_node (HF-native). | |
| The concept_node config carries each L1/L2 BERTopic node's centroid inline as a | |
| `centroid` column (bi_encoder_v1 384-dim vectors). We project to a 3-column | |
| parquet (concept_id, level, centroid) matching the historical schema. | |
| """ | |
| ds = load_hf_or_local("NuBerea/concept-graph", "concept_node") | |
| df = ds.to_pandas() | |
| df = df[df["level"].isin([1, 2])].copy() | |
| df["level"] = df["level"].map({1: "l1", 2: "l2"}) | |
| df = df[["concept_id", "level", "centroid"]].sort_values(["level", "concept_id"]).reset_index(drop=True) | |
| dst = _parquet_out("concept_centroids") | |
| df.to_parquet(dst, index=False) | |
| per_level = df.groupby("level").size().to_dict() | |
| print(f" concept_centroids: {len(df)} rows ({per_level}) — built from concept_node (HF-native)") | |
| def build_concept_drift_hamilton() -> None: | |
| """Run the Hamilton/CADE word2vec drift analysis (requires gensim). | |
| Delegates to build_hamilton.py, which trains word2vec per corpus slice, | |
| aligns via orthogonal Procrustes, and computes drift_score per shared lemma. | |
| Three independent analyses: Hebrew EBH→LBH, Greek LXX→NT, Latin VG_OT→VG_NT. | |
| Requires Python 3.12 venv with gensim installed: | |
| /tmp/gensim_venv/bin/python scripts/build_hamilton.py | |
| Or equivalently: | |
| python scripts/build.py --config concept_drift_hamilton | |
| (which calls build_hamilton.py via subprocess using the same interpreter that | |
| has gensim, or prints existing stats if the parquet already exists.) | |
| """ | |
| import subprocess | |
| import sys | |
| parquet = OUT / "concept_drift_hamilton" / "train-00000-of-00001.parquet" | |
| # Try running build_hamilton.py with current interpreter first; fall back to gensim venv | |
| interpreters = [sys.executable, "/tmp/gensim_venv/bin/python"] | |
| for interp in interpreters: | |
| try: | |
| result = subprocess.run( | |
| [interp, "scripts/build_hamilton.py"], | |
| check=True, capture_output=False, | |
| ) | |
| break | |
| except (subprocess.CalledProcessError, FileNotFoundError): | |
| continue | |
| else: | |
| if parquet.exists(): | |
| df = pd.read_parquet(parquet) | |
| print(f" concept_drift_hamilton: {len(df):,} rows (pre-built; gensim unavailable)") | |
| else: | |
| raise RuntimeError( | |
| "build_hamilton.py failed and no pre-built parquet found. " | |
| "Run: /tmp/gensim_venv/bin/python scripts/build_hamilton.py" | |
| ) | |
| return | |
| df = pd.read_parquet(parquet) | |
| print(f" concept_drift_hamilton: {len(df):,} rows — Hamilton/CADE word2vec drift") | |
| def _build_verse_bt_lookup(dag: "pd.DataFrame", nrsv: "pd.DataFrame") -> dict: | |
| """Return dict mapping OSIS verse ref (dot format) → (bt_layer, plate_segment). | |
| Covers three node types in composition_dag: | |
| - otp:/pseu: rows with osis_start/osis_end → range-expanded to constituent verses | |
| - single-verse rows (unit_id matches 'Book.ch.v') → direct mapping | |
| """ | |
| import re | |
| # Parse OSIS ref to (chapter, verse) numeric key for range comparison | |
| _osis_key_re = re.compile(r'^[^.]+\.(\d+)\.(\d+)$') | |
| def _key(ref: str) -> tuple[int, int] | None: | |
| m = _osis_key_re.match(ref) | |
| if not m: | |
| return None | |
| return (int(m.group(1)), int(m.group(2))) | |
| verse_bt: dict = {} | |
| # ── 1. Range-based: otp + pseu rows (have osis_start / osis_end) ──────── | |
| range_rows = dag[ | |
| dag['unit_id'].str.startswith(('otp:', 'pseu:'), na=False) | |
| & dag['osis_start'].ne('') | |
| ][['osis_start', 'osis_end', 'bt_layer', 'plate_segment']].copy() | |
| range_rows['_book'] = range_rows['osis_start'].str.split('.').str[0] | |
| range_rows['_sk'] = range_rows['osis_start'].apply(_key) | |
| range_rows['_ek'] = range_rows['osis_end'].apply(_key) | |
| range_rows = range_rows.dropna(subset=['_sk', '_ek']) | |
| # Build a numeric sort key for merge_asof (ch * 10000 + v fits all Bible ranges) | |
| range_rows['_start_num'] = range_rows['_sk'].apply(lambda k: k[0] * 10000 + k[1]) | |
| range_rows['_end_num'] = range_rows['_ek'].apply(lambda k: k[0] * 10000 + k[1]) | |
| nrsv_ot = nrsv[nrsv['osis_ref'].str.contains(r'^\w+\.\d+\.\d+$', regex=True, na=False)].copy() | |
| nrsv_ot['_book'] = nrsv_ot['osis_ref'].str.split('.').str[0] | |
| nrsv_ot['_num'] = nrsv_ot['osis_ref'].apply( | |
| lambda r: (lambda k: k[0] * 10000 + k[1] if k else None)(_key(r)) | |
| ) | |
| nrsv_ot = nrsv_ot.dropna(subset=['_num']) | |
| nrsv_ot['_num'] = nrsv_ot['_num'].astype(int) | |
| for book, book_perps in range_rows.groupby('_book'): | |
| book_verses = nrsv_ot[nrsv_ot['_book'] == book][['osis_ref', '_num']].sort_values('_num') | |
| if book_verses.empty: | |
| continue | |
| perps_sorted = book_perps[['_start_num', '_end_num', 'bt_layer', 'plate_segment']].sort_values('_start_num') | |
| # merge_asof: for each verse, find the last pericope whose start ≤ verse | |
| merged = pd.merge_asof( | |
| book_verses, | |
| perps_sorted, | |
| left_on='_num', | |
| right_on='_start_num', | |
| direction='backward', | |
| ) | |
| # Keep only verses that also fall before the pericope's end | |
| merged = merged[merged['_num'] <= merged['_end_num']] | |
| for _, row in merged.iterrows(): | |
| verse_bt[row['osis_ref']] = (int(row['bt_layer']), str(row['plate_segment'])) | |
| # ── 2. Single-verse nodes: unit_id IS the verse OSIS ref ─────────────── | |
| single_mask = dag['unit_id'].str.match(r'^\w+\.\d+\.\d+$', na=False) | |
| for _, row in dag[single_mask][['unit_id', 'bt_layer', 'plate_segment']].iterrows(): | |
| verse_bt[row['unit_id']] = (int(row['bt_layer']), str(row['plate_segment'])) | |
| return verse_bt | |
| def _normalize_osis(ref: str) -> str: | |
| """Convert lxx-style '1Chr 1:1' to OSIS dot-format '1Chr.1.1'.""" | |
| if ' ' in ref: | |
| book, rest = ref.split(' ', 1) | |
| return f"{book}.{rest.replace(':', '.')}" | |
| return ref | |
| def build_concept_verse_edge_bt() -> None: | |
| """Extend concept_verse_edge_sp with bt_layer and plate_segment from pericope-genealogy. | |
| Cardinal rule (CLAUDE.md): preserves ALL verse-level rows (match_grain='verse'). | |
| bt_layer is nullable (pd.NA) for NT verses not represented as intertextuality | |
| anchor nodes in composition_dag. osisRef is the normalized OSIS dot-format ref. | |
| T8 dependency: reads NuBerea/pericope-genealogy composition_dag (T7). Falls back | |
| to local build dir until genealogy HF upload is complete. | |
| """ | |
| import numpy as np | |
| cve = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_sp").to_pandas() | |
| dag = load_hf_or_local("NuBerea/analytics", "composition_dag").to_pandas() | |
| nrsv = load_hf_or_local("NuBerea/nrsv").to_pandas() | |
| verse_bt = _build_verse_bt_lookup(dag, nrsv) | |
| # Normalize all osis_refs to dot format for lookup | |
| cve['osisRef'] = cve['osis_ref'].apply(_normalize_osis) | |
| bt_layers = [] | |
| plate_segments = [] | |
| for ref in cve['osisRef']: | |
| val = verse_bt.get(ref) | |
| if val is not None: | |
| bt_layers.append(val[0]) | |
| plate_segments.append(val[1]) | |
| else: | |
| bt_layers.append(pd.NA) | |
| plate_segments.append(pd.NA) | |
| cve['bt_layer'] = pd.array(bt_layers, dtype=pd.Int64Dtype()) | |
| cve['plate_segment'] = plate_segments | |
| cve['match_grain'] = 'verse' | |
| dst = _parquet_out("concept_verse_edge_bt") | |
| cve.to_parquet(dst, index=False) | |
| matched = cve['bt_layer'].notna().sum() | |
| print( | |
| f" concept_verse_edge_bt: {len(cve):,} rows, " | |
| f"{matched:,} ({100*matched/len(cve):.1f}%) with bt_layer — " | |
| f"T8 (pericope-genealogy)" | |
| ) | |
| def build_concept_trajectory_bt() -> None: | |
| """Build concept × bt_layer centroids from concept_verse_edge_bt. | |
| Cardinal rule: pericope-level derived view (match_grain='pericope') alongside | |
| concept_trajectory_sp (3-way stratum). Never replaces it. | |
| Only rows with a non-null bt_layer contribute. Concepts with fewer than 2 | |
| matched verses in a bt_layer are excluded (no meaningful centroid). | |
| Schema mirrors concept_trajectory_sp with bt_layer replacing stratum, plus | |
| match_grain='pericope' and osisRef (book prefix of contributing verses). | |
| """ | |
| import numpy as np | |
| # Load from local build output (concept_verse_edge_bt must be built first) | |
| bt_path = _parquet_out("concept_verse_edge_bt") | |
| if not bt_path.exists(): | |
| raise RuntimeError( | |
| "concept_verse_edge_bt not found — run build_concept_verse_edge_bt first." | |
| ) | |
| cve_bt = pd.read_parquet(bt_path) | |
| # Work only on rows with bt_layer assigned | |
| matched = cve_bt[cve_bt['bt_layer'].notna()].copy() | |
| matched['bt_layer'] = matched['bt_layer'].astype(int) | |
| def _numpy_centroid(embeddings) -> list: | |
| arr = np.stack([np.asarray(e) for e in embeddings]) | |
| c = arr.mean(axis=0) | |
| return c.tolist() | |
| def _mean_cosine(embeddings, centroid) -> float: | |
| c = np.asarray(centroid) | |
| sims = [] | |
| for e in embeddings: | |
| v = np.asarray(e) | |
| denom = np.linalg.norm(v) * np.linalg.norm(c) | |
| if denom > 0: | |
| sims.append(float(np.dot(v, c) / denom)) | |
| return float(np.mean(sims)) if sims else 0.0 | |
| rows = [] | |
| for (concept_id, bt_layer), grp in matched.groupby(['concept_id', 'bt_layer']): | |
| if len(grp) < 2: | |
| continue | |
| embeddings = grp['embedding'].tolist() | |
| centroid = _numpy_centroid(embeddings) | |
| rows.append({ | |
| 'concept_id': concept_id, | |
| 'concept_label': grp['concept_label'].iloc[0], | |
| 'bt_layer': int(bt_layer), | |
| 'verse_count': len(grp), | |
| 'centroid': centroid, | |
| 'mean_cosine_to_centroid': _mean_cosine(embeddings, centroid), | |
| 'verse_refs': sorted(set(grp['osisRef'].tolist())), | |
| 'model_id': grp['model_id'].iloc[0], | |
| 'match_grain': 'pericope', | |
| }) | |
| df = pd.DataFrame(rows).sort_values(['concept_id', 'bt_layer']).reset_index(drop=True) | |
| dst = _parquet_out("concept_trajectory_bt") | |
| df.to_parquet(dst, index=False) | |
| print( | |
| f" concept_trajectory_bt: {len(df):,} rows " | |
| f"({df['concept_id'].nunique()} concepts × {df['bt_layer'].nunique()} bt_layers) — " | |
| f"T8 derived view, match_grain=pericope" | |
| ) | |
| def _build_reference_centroids() -> "tuple[list, list, np.ndarray]": | |
| """Compute per-concept reference centroids pooled from LXX+NT+VG in SPhilBerta space. | |
| Returns: | |
| (concept_ids, concept_labels, centroid_unit_matrix) | |
| centroid_unit_matrix shape: (n_concepts, 768), L2-normalized rows. | |
| """ | |
| import numpy as np | |
| print(" Loading concept_verse_edge_sp for reference centroids...") | |
| cve_sp = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_sp").to_pandas() | |
| concept_ids = [] | |
| concept_labels_list = [] | |
| centroid_list = [] | |
| for cid, grp in cve_sp.groupby("concept_id"): | |
| mats = np.stack([np.asarray(e, dtype=np.float32) for e in grp["embedding"]]) | |
| centroid_list.append(mats.mean(axis=0)) | |
| concept_ids.append(cid) | |
| concept_labels_list.append(grp["concept_label"].iloc[0]) | |
| centroid_matrix = np.stack(centroid_list) # (n_concepts, 768) | |
| norms = np.linalg.norm(centroid_matrix, axis=1, keepdims=True) | |
| centroid_unit = centroid_matrix / (norms + 1e-8) | |
| print(f" Reference space: {len(concept_ids)} concept centroids (768-dim SPhilBerta)") | |
| return concept_ids, concept_labels_list, centroid_unit | |
| def _project_pseu_stratum( | |
| stratum: str, | |
| concept_ids: list, | |
| concept_labels_list: list, | |
| centroid_unit: "np.ndarray", | |
| ) -> "pd.DataFrame": | |
| """Project one PSEU stratum onto pre-computed concept centroids. | |
| Each verse is assigned to its single nearest concept (top-1 cosine similarity). | |
| assignment_method='nearest_centroid' distinguishes these rows from topology-based | |
| pericope_containment rows in concept_verse_edge_sp. | |
| """ | |
| import numpy as np | |
| config_name = "deut_verse_embeddings_sp" if stratum == "deut" else "pseu_verse_embeddings_sp" | |
| print(f" Loading {config_name} from NuBerea/features...") | |
| pseu_df = load_hf_or_local("NuBerea/features", config_name).to_pandas() | |
| print(f" Loaded {len(pseu_df):,} {stratum} verses") | |
| emb_matrix = np.stack([np.asarray(e, dtype=np.float32) for e in pseu_df["embedding"]]) | |
| emb_norms = np.linalg.norm(emb_matrix, axis=1, keepdims=True) | |
| emb_unit = emb_matrix / (emb_norms + 1e-8) | |
| cos_scores = emb_unit @ centroid_unit.T # (n_verses, n_concepts) | |
| best_idx = cos_scores.argmax(axis=1) | |
| best_score = cos_scores[np.arange(len(pseu_df)), best_idx] | |
| rows = [] | |
| for i, (_, verse_row) in enumerate(pseu_df.iterrows()): | |
| ci = int(best_idx[i]) | |
| rows.append({ | |
| "concept_id": concept_ids[ci], | |
| "concept_label": concept_labels_list[ci], | |
| "osis_ref": verse_row["osis_ref"], | |
| "stratum": stratum, | |
| "edge_weight": float(best_score[i]), | |
| "embedding": verse_row["embedding"], | |
| "model_id": verse_row["model_id"], | |
| "assignment_method": "nearest_centroid", | |
| }) | |
| return pd.DataFrame(rows) | |
| def build_concept_verse_edge_pseu() -> None: | |
| """Build concept_verse_edge_deut and concept_verse_edge_pseu. | |
| Both use nearest-centroid projection from the pooled LXX+NT+VG concept | |
| centroids in SPhilBerta space. PSEU pericopes are not yet represented in | |
| concept-graph topology, so pericope_containment is not available for these | |
| strata. assignment_method='nearest_centroid' records this distinction. | |
| Loads the reference centroid matrix once and reuses it for both strata. | |
| """ | |
| import numpy as np | |
| concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids() | |
| for stratum in ("deut", "pseu"): | |
| config = f"concept_verse_edge_{stratum}" | |
| df = _project_pseu_stratum(stratum, concept_ids, concept_labels_list, centroid_unit) | |
| dst = _parquet_out(config) | |
| df.to_parquet(dst, index=False) | |
| concept_count = df["concept_id"].nunique() | |
| mean_score = df["edge_weight"].mean() | |
| print( | |
| f" {config}: {len(df):,} rows " | |
| f"({concept_count} unique concepts, mean cosine={mean_score:.4f})" | |
| ) | |
| def build_concept_trajectory_pseu() -> None: | |
| """Build concept_trajectory_deut and concept_trajectory_pseu. | |
| Aggregates concept_verse_edge_deut/pseu to per-concept centroids. | |
| build_concept_verse_edge_pseu must be run first. | |
| """ | |
| import numpy as np | |
| for stratum in ("deut", "pseu"): | |
| edge_path = _parquet_out(f"concept_verse_edge_{stratum}") | |
| if not edge_path.exists(): | |
| raise RuntimeError( | |
| f"concept_verse_edge_{stratum} not found — run build_concept_verse_edge_pseu first." | |
| ) | |
| cve = pd.read_parquet(edge_path) | |
| rows = [] | |
| for cid, grp in cve.groupby("concept_id"): | |
| mats = np.stack([np.asarray(e, dtype=np.float32) for e in grp["embedding"]]) | |
| centroid = mats.mean(axis=0) | |
| cnorm = np.linalg.norm(centroid) | |
| centroid_unit = centroid / (cnorm + 1e-8) | |
| norms = np.linalg.norm(mats, axis=1, keepdims=True) | |
| units = mats / (norms + 1e-8) | |
| mean_cos = float((units @ centroid_unit).mean()) | |
| rows.append({ | |
| "concept_id": cid, | |
| "concept_label": grp["concept_label"].iloc[0], | |
| "stratum": stratum, | |
| "verse_count": len(grp), | |
| "centroid": centroid.tolist(), | |
| "mean_cosine_to_centroid": mean_cos, | |
| "verse_refs": grp["osis_ref"].tolist(), | |
| "model_id": grp["model_id"].iloc[0], | |
| "assignment_method": "nearest_centroid", | |
| }) | |
| df = pd.DataFrame(rows).sort_values("concept_id").reset_index(drop=True) | |
| config = f"concept_trajectory_{stratum}" | |
| dst = _parquet_out(config) | |
| df.to_parquet(dst, index=False) | |
| mean_cos_all = df["mean_cosine_to_centroid"].mean() | |
| print( | |
| f" {config}: {len(df):,} rows " | |
| f"({df['concept_id'].nunique()} concepts, mean coherence={mean_cos_all:.4f})" | |
| ) | |
| def build_concept_drift_pseu() -> None: | |
| """Compute PSEU-extended drift metrics across 5 new stratum transition pairs. | |
| Pairs: lxx→deut, lxx→pseu, deut→nt, pseu→nt, deut→pseu. | |
| Mirrors the Schlattmann & Vogl 2024 methodology used in build_concept_drift(), | |
| extending to LXX Deuterocanon (stratum 6) and Second Temple Pseudepigrapha (stratum 7). | |
| Inputs: | |
| NuBerea/concept-trajectories concept_trajectory_sp — lxx/nt/vg centroids | |
| NuBerea/concept-trajectories concept_verse_edge_sp — lxx/nt/vg embeddings | |
| NuBerea/concept-analysis concept_trajectory_deut — deut centroids (PSEU) | |
| NuBerea/concept-analysis concept_trajectory_pseu — pseu centroids (PSEU) | |
| NuBerea/concept-analysis concept_verse_edge_deut — deut embeddings (PSEU) | |
| NuBerea/concept-analysis concept_verse_edge_pseu — pseu embeddings (PSEU) | |
| Output: 78 rows (one per concept); wide format with per-stratum crystallization | |
| and per-pair cross-stratum drift metrics. | |
| """ | |
| import numpy as np | |
| sys.path.insert(0, str(_THIS.parent)) | |
| from analyze_concept_drift import cosine_sim, cross_density | |
| traj_sp = load_hf_or_local("NuBerea/concept-analysis", "concept_trajectory_sp").to_pandas() | |
| traj_deut = load_hf_or_local("NuBerea/concept-analysis", "concept_trajectory_deut").to_pandas() | |
| traj_pseu = load_hf_or_local("NuBerea/concept-analysis", "concept_trajectory_pseu").to_pandas() | |
| traj_all = pd.concat([traj_sp, traj_deut, traj_pseu], ignore_index=True) | |
| traj_idx = traj_all.set_index(["concept_id", "stratum"]) | |
| cve_sp = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_sp").to_pandas() | |
| cve_deut = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_deut").to_pandas() | |
| cve_pseu = load_hf_or_local("NuBerea/concept-analysis", "concept_verse_edge_pseu").to_pandas() | |
| cve_all = pd.concat([cve_sp, cve_deut, cve_pseu], ignore_index=True) | |
| emb_index: dict[tuple, np.ndarray] = {} | |
| for (cid, stratum), grp in cve_all.groupby(["concept_id", "stratum"]): | |
| emb_index[(cid, stratum)] = np.stack( | |
| [np.array(e, dtype=np.float32) for e in grp["embedding"]] | |
| ) | |
| all_concepts = traj_sp["concept_id"].unique() | |
| concept_label = ( | |
| traj_sp.drop_duplicates("concept_id") | |
| .set_index("concept_id")["concept_label"] | |
| .to_dict() | |
| ) | |
| pseu_pairs = [ | |
| ("lxx", "deut"), ("lxx", "pseu"), | |
| ("deut", "nt"), ("pseu", "nt"), | |
| ("deut", "pseu"), | |
| ] | |
| all_strata = ["lxx", "nt", "vg", "deut", "pseu"] | |
| records = [] | |
| for cid in all_concepts: | |
| label = concept_label.get(cid, "") | |
| row: dict = {"concept_id": cid, "concept_label": label} | |
| for s in all_strata: | |
| key = (cid, s) | |
| if key in traj_idx.index: | |
| row[f"verse_count_{s}"] = int(traj_idx.loc[key, "verse_count"]) | |
| row[f"crystallization_{s}"] = float(traj_idx.loc[key, "mean_cosine_to_centroid"]) | |
| row[f"dispersion_{s}"] = 1.0 - row[f"crystallization_{s}"] | |
| else: | |
| row[f"verse_count_{s}"] = 0 | |
| row[f"crystallization_{s}"] = float("nan") | |
| row[f"dispersion_{s}"] = float("nan") | |
| for s_a, s_b in pseu_pairs: | |
| tag = f"{s_a}_{s_b}" | |
| key_a = (cid, s_a) | |
| key_b = (cid, s_b) | |
| have_a = key_a in traj_idx.index | |
| have_b = key_b in traj_idx.index | |
| if have_a and have_b: | |
| c_a = np.array(traj_idx.loc[key_a, "centroid"], dtype=np.float32) | |
| c_b = np.array(traj_idx.loc[key_b, "centroid"], dtype=np.float32) | |
| cc = cosine_sim(c_a, c_b) | |
| row[f"centroid_cosine_{tag}"] = cc | |
| row[f"centroid_drift_{tag}"] = 1.0 - cc | |
| else: | |
| row[f"centroid_cosine_{tag}"] = float("nan") | |
| row[f"centroid_drift_{tag}"] = float("nan") | |
| d_a = row[f"dispersion_{s_a}"] | |
| d_b = row[f"dispersion_{s_b}"] | |
| row[f"delta_dispersion_{tag}"] = ( | |
| d_b - d_a | |
| if (not np.isnan(d_a) and not np.isnan(d_b)) | |
| else float("nan") | |
| ) | |
| if have_a and key_b in emb_index: | |
| c_a = np.array(traj_idx.loc[key_a, "centroid"], dtype=np.float32) | |
| emb_b = emb_index[key_b] | |
| cd_ab = cross_density(emb_b, c_a) | |
| row[f"cross_density_{tag}"] = cd_ab | |
| row[f"cross_drift_{tag}"] = 1.0 - cd_ab | |
| else: | |
| row[f"cross_density_{tag}"] = float("nan") | |
| row[f"cross_drift_{tag}"] = float("nan") | |
| if have_b and key_a in emb_index: | |
| c_b = np.array(traj_idx.loc[key_b, "centroid"], dtype=np.float32) | |
| emb_a = emb_index[key_a] | |
| row[f"cross_density_{s_b}_{s_a}"] = cross_density(emb_a, c_b) | |
| else: | |
| row[f"cross_density_{s_b}_{s_a}"] = float("nan") | |
| cd_tag = row[f"centroid_drift_{tag}"] | |
| xd_tag = row[f"cross_drift_{tag}"] | |
| both_ok = not np.isnan(cd_tag) and not np.isnan(xd_tag) | |
| row[f"drift_score_{tag}"] = (cd_tag + xd_tag) / 2.0 if both_ok else float("nan") | |
| records.append(row) | |
| df = pd.DataFrame(records) | |
| dst = _parquet_out("concept_drift_itp") | |
| df.to_parquet(dst, index=False) | |
| print(f" concept_drift_itp: {len(df)} rows, {len(df.columns)} cols — 5 PSEU drift pairs (lxx→deut/pseu, deut/pseu→nt, deut→pseu)") | |
| def build_concept_aliases() -> None: | |
| """Build concept_aliases (TF-IDF English term → bt1_xxx mapping) from HF inputs. | |
| Fully HF-native: loads bi_encoder_v1 + question_bin_assignment.json from | |
| NuBerea/AI-models and L1 centroids from NuBerea/concept-graph, then runs the | |
| BERTopic alias TF-IDF logic. See build_aliases_from_hf.py for details. | |
| """ | |
| from build_aliases_from_hf import build_aliases_dataframe | |
| df = build_aliases_dataframe() | |
| dst = _parquet_out("concept_aliases") | |
| df.to_parquet(dst, index=False) | |
| print(f" concept_aliases: {len(df)} rows, {len(df.columns)} cols — built HF-native") | |
| def build_concept_verse_edge_patr() -> None: | |
| """Project patristic GRC segments onto concept centroids via nearest-centroid assignment. | |
| Loads pre-computed SPhilBerta embeddings from NuBerea/features | |
| (patr_grc_embeddings_sp, ~40K rows) and assigns each segment to its | |
| nearest concept from the pooled LXX+NT+VG reference centroids. | |
| Output schema matches concept_verse_edge_pseu but uses `segment_id` instead | |
| of `osis_ref` and adds `cts_urn`, `author_label`, and `family_id` fields | |
| for downstream patristic-specific joins. | |
| """ | |
| import numpy as np | |
| concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids() | |
| print(" Loading patristics embeddings from NuBerea/features (patr_grc_embeddings_sp)...") | |
| patr_df = load_hf_or_local("NuBerea/features", "patr_grc_embeddings_sp").to_pandas() | |
| print(f" Loaded {len(patr_df):,} patristic GRC segments") | |
| emb_matrix = np.stack([np.asarray(e, dtype=np.float32) for e in patr_df["embedding"]]) | |
| emb_norms = np.linalg.norm(emb_matrix, axis=1, keepdims=True) | |
| emb_unit = emb_matrix / (emb_norms + 1e-8) | |
| cos_scores = emb_unit @ centroid_unit.T # (n_segments, n_concepts) | |
| best_idx = cos_scores.argmax(axis=1) | |
| best_score = cos_scores[np.arange(len(patr_df)), best_idx] | |
| rows = [] | |
| for i, (_, seg_row) in enumerate(patr_df.iterrows()): | |
| ci = int(best_idx[i]) | |
| rows.append({ | |
| "concept_id": concept_ids[ci], | |
| "concept_label": concept_labels_list[ci], | |
| "segment_id": seg_row["segment_id"], | |
| "cts_urn": seg_row["cts_urn"], | |
| "author_label": seg_row["author_label"], | |
| "family_id": seg_row["family_id"], | |
| "stratum": "patr", | |
| "edge_weight": float(best_score[i]), | |
| "embedding": seg_row["embedding"], | |
| "model_id": seg_row["model_id"], | |
| "assignment_method": "nearest_centroid", | |
| }) | |
| df = pd.DataFrame(rows) | |
| dst = _parquet_out("concept_verse_edge_patr") | |
| df.to_parquet(dst, index=False) | |
| concept_count = df["concept_id"].nunique() | |
| mean_score = df["edge_weight"].mean() | |
| print( | |
| f" concept_verse_edge_patr: {len(df):,} rows " | |
| f"({concept_count} unique concepts, mean cosine={mean_score:.4f}, " | |
| f"{df['family_id'].nunique()} families)" | |
| ) | |
| _TARGUM_OSIS_MAP: dict[str, str] = { | |
| # Torah | |
| "Genesis": "Gen", "Exodus": "Exod", "Leviticus": "Lev", | |
| "Numbers": "Num", "Deuteronomy": "Deut", | |
| # Former Prophets | |
| "Joshua": "Josh", "Judges": "Judg", "Ruth": "Ruth", | |
| "I Samuel": "1Sam", "II Samuel": "2Sam", | |
| "I Kings": "1Kgs", "II Kings": "2Kgs", | |
| # Latter Prophets | |
| "Isaiah": "Isa", "Jeremiah": "Jer", "Ezekiel": "Ezek", | |
| "Hosea": "Hos", "Joel": "Joel", "Amos": "Amos", "Obadiah": "Obad", | |
| "Jonah": "Jonah", "Micah": "Mic", "Nahum": "Nah", "Habakkuk": "Hab", | |
| "Zephaniah": "Zeph", "Haggai": "Hag", "Zechariah": "Zech", "Malachi": "Mal", | |
| # Writings | |
| "Psalms": "Ps", "Proverbs": "Prov", "Job": "Job", | |
| "Song of Songs": "Song", "Lamentations": "Lam", "Ecclesiastes": "Eccl", | |
| "Esther": "Esth", "Daniel": "Dan", "Ezra": "Ezra", "Nehemiah": "Neh", | |
| "I Chronicles": "1Chr", "II Chronicles": "2Chr", | |
| } | |
| def _embed_texts_sphilberta(texts: list[str], batch_size: int = 32) -> tuple: | |
| """Embed texts with SPhilBerta. Returns (vecs: np.ndarray float32, model_id: str).""" | |
| from sentence_transformers import SentenceTransformer | |
| import torch | |
| model_id = "bowphs/SPhilBerta" | |
| if torch.backends.mps.is_available(): | |
| device = "mps" | |
| elif torch.cuda.is_available(): | |
| device = "cuda" | |
| else: | |
| device = "cpu" | |
| print(f" Loading {model_id} on {device}...") | |
| model = SentenceTransformer(model_id, device=device) | |
| print(f" Embedding {len(texts):,} texts (batch_size={batch_size})...") | |
| vecs = model.encode( | |
| texts, | |
| batch_size=batch_size, | |
| show_progress_bar=True, | |
| normalize_embeddings=False, | |
| convert_to_numpy=True, | |
| ) | |
| return vecs.astype("float32"), model_id | |
| def build_concept_verse_edge_philo() -> None: | |
| """Project Philo of Alexandria GRC segments onto concept centroids. | |
| Loads philo_grc from NuBerea/secondary-sources (7,906 rows), embeds with | |
| SPhilBerta, and assigns each segment to its nearest concept centroid. | |
| Schema mirrors concept_verse_edge_patr. | |
| """ | |
| import numpy as np | |
| concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids() | |
| print(" Loading philo_grc from NuBerea/secondary-sources...") | |
| philo_df = load_hf_or_local("NuBerea/secondary-sources", "philo_grc").to_pandas() | |
| print(f" Loaded {len(philo_df):,} Philo segments") | |
| vecs, model_id = _embed_texts_sphilberta(philo_df["text"].tolist()) | |
| norms = np.linalg.norm(vecs, axis=1, keepdims=True) | |
| vecs_unit = vecs / (norms + 1e-8) | |
| cos_scores = vecs_unit @ centroid_unit.T | |
| best_idx = cos_scores.argmax(axis=1) | |
| best_score = cos_scores[np.arange(len(philo_df)), best_idx] | |
| rows = [] | |
| for i, (_, seg) in enumerate(philo_df.iterrows()): | |
| ci = int(best_idx[i]) | |
| rows.append({ | |
| "concept_id": concept_ids[ci], | |
| "concept_label": concept_labels_list[ci], | |
| "segment_id": seg["segment_id"], | |
| "cts_urn": seg["cts_urn"], | |
| "author_label": seg["author_label"], | |
| "work_label": seg["work_label"], | |
| "stratum": "philo", | |
| "edge_weight": float(best_score[i]), | |
| "embedding": vecs[i], | |
| "model_id": model_id, | |
| "assignment_method": "nearest_centroid", | |
| }) | |
| df = pd.DataFrame(rows) | |
| dst = _parquet_out("concept_verse_edge_philo") | |
| df.to_parquet(dst, index=False) | |
| concept_count = df["concept_id"].nunique() | |
| mean_score = df["edge_weight"].mean() | |
| print( | |
| f" concept_verse_edge_philo: {len(df):,} rows " | |
| f"({concept_count} unique concepts, mean cosine={mean_score:.4f})" | |
| ) | |
| def build_concept_verse_edge_josephus() -> None: | |
| """Project Josephus GRC segments onto concept centroids. | |
| Loads josephus_grc from NuBerea/secondary-sources (12,735 rows), embeds with | |
| SPhilBerta, and assigns each segment to its nearest concept centroid. | |
| """ | |
| import numpy as np | |
| concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids() | |
| print(" Loading josephus_grc from NuBerea/secondary-sources...") | |
| jos_df = load_hf_or_local("NuBerea/secondary-sources", "josephus_grc").to_pandas() | |
| print(f" Loaded {len(jos_df):,} Josephus segments") | |
| vecs, model_id = _embed_texts_sphilberta(jos_df["text"].tolist()) | |
| norms = np.linalg.norm(vecs, axis=1, keepdims=True) | |
| vecs_unit = vecs / (norms + 1e-8) | |
| cos_scores = vecs_unit @ centroid_unit.T | |
| best_idx = cos_scores.argmax(axis=1) | |
| best_score = cos_scores[np.arange(len(jos_df)), best_idx] | |
| rows = [] | |
| for i, (_, seg) in enumerate(jos_df.iterrows()): | |
| ci = int(best_idx[i]) | |
| rows.append({ | |
| "concept_id": concept_ids[ci], | |
| "concept_label": concept_labels_list[ci], | |
| "segment_id": seg["segment_id"], | |
| "cts_urn": seg["cts_urn"], | |
| "author_label": seg["author_label"], | |
| "work_label": seg["work_label"], | |
| "stratum": "josephus", | |
| "edge_weight": float(best_score[i]), | |
| "embedding": vecs[i], | |
| "model_id": model_id, | |
| "assignment_method": "nearest_centroid", | |
| }) | |
| df = pd.DataFrame(rows) | |
| dst = _parquet_out("concept_verse_edge_josephus") | |
| df.to_parquet(dst, index=False) | |
| concept_count = df["concept_id"].nunique() | |
| mean_score = df["edge_weight"].mean() | |
| print( | |
| f" concept_verse_edge_josephus: {len(df):,} rows " | |
| f"({concept_count} unique concepts, mean cosine={mean_score:.4f})" | |
| ) | |
| def build_concept_verse_edge_targum() -> None: | |
| """Project Targum (Aramaic OT paraphrase) English translations onto concept centroids. | |
| Loads targum config from NuBerea/second-temple (~28K rows), embeds text_en | |
| with SPhilBerta (Aramaic is unvalidated; English preserves interpretive content), | |
| and assigns each verse to its nearest concept centroid. Derives canonical osis_ref | |
| from book + section_0 (chapter) + section_1 (verse) for downstream pericope joins. | |
| """ | |
| import numpy as np | |
| concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids() | |
| print(" Loading targum from NuBerea/second-temple...") | |
| tg_df = load_hf_or_local("NuBerea/second-temple", "targum").to_pandas() | |
| print(f" Loaded {len(tg_df):,} Targum rows") | |
| # Drop rows with no English translation | |
| tg_df = tg_df[tg_df["text_en"].notna() & (tg_df["text_en"].str.strip() != "")].copy() | |
| print(f" {len(tg_df):,} rows with text_en available") | |
| texts = tg_df["text_en"].tolist() | |
| vecs, model_id = _embed_texts_sphilberta(texts) | |
| norms = np.linalg.norm(vecs, axis=1, keepdims=True) | |
| vecs_unit = vecs / (norms + 1e-8) | |
| cos_scores = vecs_unit @ centroid_unit.T | |
| best_idx = cos_scores.argmax(axis=1) | |
| best_score = cos_scores[np.arange(len(tg_df)), best_idx] | |
| def _osis_book_from_targum(book: str, targum_name: str | None) -> str | None: | |
| osis = _TARGUM_OSIS_MAP.get(book) | |
| if osis: | |
| return osis | |
| # book is typically "{targum_name} {canonical_name}" — strip the prefix | |
| prefix = (targum_name or "").strip() | |
| if prefix and book.startswith(prefix + " "): | |
| osis = _TARGUM_OSIS_MAP.get(book[len(prefix) + 1:]) | |
| if osis: | |
| return osis | |
| # Fallback: try each word-count suffix (handles unexpected prefix variants) | |
| words = book.split() | |
| for skip in range(1, len(words)): | |
| osis = _TARGUM_OSIS_MAP.get(" ".join(words[skip:])) | |
| if osis: | |
| return osis | |
| return None | |
| rows = [] | |
| for i, (_, seg) in enumerate(tg_df.iterrows()): | |
| ci = int(best_idx[i]) | |
| book = seg.get("book") or "" | |
| targum_name = seg.get("targum_name") | |
| osis_book = _osis_book_from_targum(book, targum_name) | |
| s0 = seg.get("section_0") | |
| s1 = seg.get("section_1") | |
| if osis_book and s0 is not None and s1 is not None: | |
| osis_ref = f"{osis_book}.{int(s0) + 1}.{int(s1) + 1}" | |
| elif osis_book and s0 is not None: | |
| osis_ref = f"{osis_book}.{int(s0) + 1}" | |
| else: | |
| osis_ref = None | |
| rows.append({ | |
| "concept_id": concept_ids[ci], | |
| "concept_label": concept_labels_list[ci], | |
| "segment_id": seg["segment_id"], | |
| "osis_ref": osis_ref, | |
| "targum_name": seg.get("targum_name"), | |
| "section": seg.get("section"), | |
| "book": book, | |
| "stratum": "targum", | |
| "edge_weight": float(best_score[i]), | |
| "embedding": vecs[i], | |
| "model_id": model_id, | |
| "assignment_method": "nearest_centroid", | |
| }) | |
| df = pd.DataFrame(rows) | |
| dst = _parquet_out("concept_verse_edge_targum") | |
| df.to_parquet(dst, index=False) | |
| concept_count = df["concept_id"].nunique() | |
| mean_score = df["edge_weight"].mean() | |
| osis_coverage = df["osis_ref"].notna().mean() | |
| print( | |
| f" concept_verse_edge_targum: {len(df):,} rows " | |
| f"({concept_count} unique concepts, mean cosine={mean_score:.4f}, " | |
| f"osis_ref coverage={osis_coverage:.1%})" | |
| ) | |
| def build_concept_verse_edge_talmud() -> None: | |
| """Project Talmud English translations onto concept centroids. | |
| Reads mishnah and tosefta directly from NuBerea/talmud via HfFileSystem | |
| (load_dataset fails on this repo; parquets are read directly). Bavli and | |
| yerushalmi are skipped until their parquets are uploaded. Embeds text_en | |
| with SPhilBerta (Mishnaic Hebrew and Talmudic Aramaic are unembeddable | |
| directly; English translations preserve interpretive content). | |
| Stratum values: mishnah (~200 CE), tosefta (~220 CE). | |
| """ | |
| import numpy as np | |
| from huggingface_hub import HfFileSystem | |
| concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids() | |
| fs = HfFileSystem() | |
| _TALMUD_PATHS = [ | |
| ("datasets/NuBerea/talmud/data/mishnah/train-00000-of-00001.parquet", "mishnah"), | |
| ("datasets/NuBerea/talmud/data/tosefta/train-00000-of-00001.parquet", "tosefta"), | |
| ] | |
| all_dfs: list[pd.DataFrame] = [] | |
| for hf_path, stratum in _TALMUD_PATHS: | |
| try: | |
| df = pd.read_parquet(fs.open(hf_path)) | |
| except Exception as e: # noqa: BLE001 best-effort catch (logs/records) | |
| print(f" Skipping talmud/{stratum}: {e}") | |
| continue | |
| if len(df) == 0: | |
| print(f" Skipping talmud/{stratum}: empty") | |
| continue | |
| total = len(df) | |
| df = df[df["text_en"].notna() & (df["text_en"].str.strip() != "")].copy() | |
| df["_stratum"] = stratum | |
| print(f" talmud/{stratum}: {len(df):,} rows with text_en (of {total:,} total)") | |
| all_dfs.append(df) | |
| if not all_dfs: | |
| print(" No Talmud data available — skipping") | |
| return | |
| combined = pd.concat(all_dfs, ignore_index=True) | |
| print(f" Total: {len(combined):,} Talmud rows across {len(all_dfs)} config(s)") | |
| texts = combined["text_en"].tolist() | |
| vecs, model_id = _embed_texts_sphilberta(texts, batch_size=128) | |
| norms = np.linalg.norm(vecs, axis=1, keepdims=True) | |
| vecs_unit = vecs / (norms + 1e-8) | |
| cos_scores = vecs_unit @ centroid_unit.T | |
| best_idx = cos_scores.argmax(axis=1) | |
| best_score = cos_scores[np.arange(len(combined)), best_idx] | |
| rows = [] | |
| for i, (_, seg) in enumerate(combined.iterrows()): | |
| ci = int(best_idx[i]) | |
| rows.append({ | |
| "concept_id": concept_ids[ci], | |
| "concept_label": concept_labels_list[ci], | |
| "segment_id": seg["segment_id"], | |
| "ref": seg.get("ref"), | |
| "title": seg.get("title"), | |
| "tractate": seg.get("tractate"), | |
| "order": seg.get("order"), | |
| "stratum": seg["_stratum"], | |
| "edge_weight": float(best_score[i]), | |
| "embedding": vecs[i], | |
| "model_id": model_id, | |
| "assignment_method": "nearest_centroid", | |
| }) | |
| df_out = pd.DataFrame(rows) | |
| dst = _parquet_out("concept_verse_edge_talmud") | |
| df_out.to_parquet(dst, index=False) | |
| concept_count = df_out["concept_id"].nunique() | |
| mean_score = df_out["edge_weight"].mean() | |
| strata = df_out["stratum"].value_counts().to_dict() | |
| print( | |
| f" concept_verse_edge_talmud: {len(df_out):,} rows " | |
| f"({concept_count} unique concepts, mean cosine={mean_score:.4f})" | |
| ) | |
| print(f" Strata: {strata}") | |
| def build_concept_verse_edge_nhc() -> None: | |
| """Project Nag Hammadi Corpus segments onto concept centroids. | |
| Reuses pre-computed SPhilBerta embeddings from NuBerea/features → | |
| gnostic_ln_bridge rather than re-running inference. The embedding | |
| column is a 768-dim float32 vector already L2-normalised at build time. | |
| """ | |
| import numpy as np | |
| from datasets import load_dataset | |
| concept_ids, concept_labels_list, centroid_unit = _build_reference_centroids() | |
| ds = load_dataset("NuBerea/features", "gnostic_ln_bridge", split="train") | |
| df = ds.to_pandas() | |
| emb_col = df["embedding"].tolist() | |
| vecs = np.array(emb_col, dtype=np.float32) | |
| norms = np.linalg.norm(vecs, axis=1, keepdims=True) | |
| vecs_unit = vecs / (norms + 1e-8) | |
| cos_scores = vecs_unit @ centroid_unit.T | |
| best_idx = cos_scores.argmax(axis=1) | |
| best_score = cos_scores[np.arange(len(df)), best_idx] | |
| rows = [] | |
| for i, (_, seg) in enumerate(df.iterrows()): | |
| ci = int(best_idx[i]) | |
| rows.append({ | |
| "concept_id": concept_ids[ci], | |
| "concept_label": concept_labels_list[ci], | |
| "segment_id": seg["segment_id"], | |
| "codex": seg.get("codex"), | |
| "tractate_num": seg.get("tractate_num"), | |
| "work_slug": seg.get("work_slug"), | |
| "work_title": seg.get("work_title"), | |
| "stratum": "nhc", | |
| "edge_weight": float(best_score[i]), | |
| "embedding": vecs[i], | |
| "model_id": "bowphs/SPhilBerta", | |
| "assignment_method": "nearest_centroid", | |
| }) | |
| df_out = pd.DataFrame(rows) | |
| dst = _parquet_out("concept_verse_edge_nhc") | |
| df_out.to_parquet(dst, index=False) | |
| concept_count = df_out["concept_id"].nunique() | |
| mean_score = df_out["edge_weight"].mean() | |
| print( | |
| f" concept_verse_edge_nhc: {len(df_out):,} rows " | |
| f"({concept_count} unique concepts, mean cosine={mean_score:.4f})" | |
| ) | |
| # ────────────────────────────────────────────────────────────────────────────── | |
| # concept_trajectory_series + concept_drift_sequential | |
| # Corpus-timeline view: per-concept centroids across 11 strata in temporal order | |
| # (OT-LXX → PSEU → Philo/Josephus → NT → Patristics → Targum/Mishnah/Tosefta → VG) | |
| # ────────────────────────────────────────────────────────────────────────────── | |
| _SERIES_STRATA = [ | |
| # (stratum_name, stratum_order, language, edge_config, stratum_filter) | |
| # stratum_filter: column value to select when one config covers multiple strata | |
| ("lxx", 1, "grc", "concept_verse_edge_sp", "lxx"), | |
| ("deut", 2, "grc", "concept_verse_edge_deut", None), | |
| ("pseu", 3, "grc", "concept_verse_edge_pseu", None), | |
| ("philo", 4, "grc", "concept_verse_edge_philo", None), | |
| ("nt", 5, "grc", "concept_verse_edge_sp", "nt"), | |
| ("josephus", 6, "grc", "concept_verse_edge_josephus", None), | |
| ("patr", 7, "grc", "concept_verse_edge_patr", None), | |
| ("targum", 8, "en", "concept_verse_edge_targum", None), | |
| ("mishnah", 9, "en", "concept_verse_edge_talmud", "mishnah"), | |
| ("tosefta", 10, "en", "concept_verse_edge_talmud", "tosefta"), | |
| ("vg", 11, "lat", "concept_verse_edge_sp", "vg"), | |
| ] | |
| _SERIES_PAIRS = [ | |
| # (stratum_a, stratum_b, pair_order) | |
| # patr→targum (pair 7) and tosefta→vg (pair 10) are cross-language | |
| ("lxx", "deut", 1), | |
| ("deut", "pseu", 2), | |
| ("pseu", "philo", 3), | |
| ("philo", "nt", 4), | |
| ("nt", "josephus", 5), | |
| ("josephus", "patr", 6), | |
| ("patr", "targum", 7), | |
| ("targum", "mishnah", 8), | |
| ("mishnah", "tosefta", 9), | |
| ("tosefta", "vg", 10), | |
| ] | |
| def build_concept_trajectory_series() -> None: | |
| """Per-concept centroids across all 11 strata in temporal order. | |
| Long format: ~858 rows (78 concepts × up to 11 strata). | |
| Crystallization = mean cosine of member embeddings to their own per-stratum centroid. | |
| mean_edge_weight = mean cosine to the reference centroid (pooled LXX+NT+VG). | |
| Strata with no segments for a concept are omitted (so row count may be <858). | |
| concept_verse_edge_sp is loaded once and reused for lxx, nt, vg strata. | |
| concept_verse_edge_talmud is loaded once and reused for mishnah, tosefta strata. | |
| """ | |
| import numpy as np | |
| _cache: dict[str, pd.DataFrame] = {} | |
| all_rows: list[dict] = [] | |
| for stratum, stratum_order, language, edge_config, stratum_filter in _SERIES_STRATA: | |
| print(f" [{stratum_order}/11] {stratum} ← {edge_config}...") | |
| if edge_config not in _cache: | |
| _cache[edge_config] = load_hf_or_local( | |
| "NuBerea/concept-analysis", edge_config | |
| ).to_pandas() | |
| df = _cache[edge_config].copy() | |
| if stratum_filter is not None: | |
| df = df[df["stratum"] == stratum_filter] | |
| if len(df) == 0: | |
| print(f" Skipping {stratum}: no rows") | |
| continue | |
| model_id = str(df["model_id"].iloc[0]) if "model_id" in df.columns else "SPhilBerta" | |
| for cid, grp in df.groupby("concept_id"): | |
| embs = np.stack([np.asarray(e, dtype=np.float32) for e in grp["embedding"]]) | |
| centroid = embs.mean(axis=0) | |
| cnorm = np.linalg.norm(centroid) | |
| centroid_unit = centroid / (cnorm + 1e-8) | |
| norms = np.linalg.norm(embs, axis=1, keepdims=True) | |
| units = embs / (norms + 1e-8) | |
| crystallization = float((units @ centroid_unit).mean()) | |
| all_rows.append({ | |
| "concept_id": cid, | |
| "concept_label": grp["concept_label"].iloc[0], | |
| "stratum": stratum, | |
| "stratum_order": stratum_order, | |
| "language": language, | |
| "verse_count": len(grp), | |
| "mean_edge_weight": float(grp["edge_weight"].mean()), | |
| "crystallization": crystallization, | |
| "centroid": centroid.tolist(), | |
| "model_id": model_id, | |
| }) | |
| n_concepts = df["concept_id"].nunique() | |
| print(f" {stratum}: {len(df):,} segments → {n_concepts} concept groups") | |
| result = ( | |
| pd.DataFrame(all_rows) | |
| .sort_values(["concept_id", "stratum_order"]) | |
| .reset_index(drop=True) | |
| ) | |
| dst = _parquet_out("concept_trajectory_series") | |
| result.to_parquet(dst, index=False) | |
| print( | |
| f" concept_trajectory_series: {len(result):,} rows " | |
| f"({result['concept_id'].nunique()} concepts × " | |
| f"{result['stratum'].nunique()} strata)" | |
| ) | |
| def build_concept_drift_sequential() -> None: | |
| """Adjacent-pair drift across the 11-stratum corpus timeline. | |
| Reads concept_trajectory_series (must be built first). | |
| Outputs ~780 rows (78 concepts × 10 adjacent pairs). | |
| same_language=False marks cross-language pairs (patr→targum, tosefta→vg) | |
| where centroid_drift is confounded by model-language mismatch. | |
| centroid_drift = 1 − cosine(centroid_a, centroid_b); range [0, 2]. | |
| delta_crystallization = crystallization_b − crystallization_a. | |
| delta_mean_edge_weight = mean_edge_weight_b − mean_edge_weight_a. | |
| """ | |
| import numpy as np | |
| series_path = _parquet_out("concept_trajectory_series") | |
| if not series_path.exists(): | |
| raise RuntimeError( | |
| "concept_trajectory_series not found — " | |
| "run build_concept_trajectory_series first." | |
| ) | |
| traj = pd.read_parquet(series_path) | |
| traj_idx = traj.set_index(["concept_id", "stratum"]) | |
| lang_map = traj.drop_duplicates("stratum").set_index("stratum")["language"].to_dict() | |
| concept_ids = traj["concept_id"].unique() | |
| all_rows: list[dict] = [] | |
| for stratum_a, stratum_b, pair_order in _SERIES_PAIRS: | |
| lang_a = lang_map.get(stratum_a, "?") | |
| lang_b = lang_map.get(stratum_b, "?") | |
| for cid in concept_ids: | |
| try: | |
| row_a = traj_idx.loc[(cid, stratum_a)] | |
| row_b = traj_idx.loc[(cid, stratum_b)] | |
| except KeyError: | |
| continue | |
| c_a = np.asarray(row_a["centroid"], dtype=np.float32) | |
| c_b = np.asarray(row_b["centroid"], dtype=np.float32) | |
| c_a_u = c_a / (np.linalg.norm(c_a) + 1e-8) | |
| c_b_u = c_b / (np.linalg.norm(c_b) + 1e-8) | |
| cos_sim = float(np.dot(c_a_u, c_b_u)) | |
| all_rows.append({ | |
| "concept_id": cid, | |
| "concept_label": row_a["concept_label"], | |
| "stratum_a": stratum_a, | |
| "stratum_b": stratum_b, | |
| "pair_order": pair_order, | |
| "language_a": lang_a, | |
| "language_b": lang_b, | |
| "same_language": lang_a == lang_b, | |
| "centroid_cosine": cos_sim, | |
| "centroid_drift": 1.0 - cos_sim, | |
| "delta_crystallization": float(row_b["crystallization"] - row_a["crystallization"]), | |
| "delta_mean_edge_weight": float(row_b["mean_edge_weight"] - row_a["mean_edge_weight"]), | |
| }) | |
| result = ( | |
| pd.DataFrame(all_rows) | |
| .sort_values(["concept_id", "pair_order"]) | |
| .reset_index(drop=True) | |
| ) | |
| dst = _parquet_out("concept_drift_sequential") | |
| result.to_parquet(dst, index=False) | |
| n_pairs = result["pair_order"].nunique() | |
| same_lang_count = int(result["same_language"].sum()) | |
| print( | |
| f" concept_drift_sequential: {len(result):,} rows " | |
| f"({n_pairs} pairs × ~{len(result) // max(n_pairs, 1)} concepts; " | |
| f"{same_lang_count} same-language rows)" | |
| ) | |
| CONFIGS = { | |
| "concept_verse_edge": lambda: import_trajectory_config("concept_verse_edge"), | |
| "concept_trajectory": lambda: import_trajectory_config("concept_trajectory"), | |
| "concept_verse_edge_sp": lambda: import_trajectory_config("concept_verse_edge_sp"), | |
| "concept_trajectory_sp": lambda: import_trajectory_config("concept_trajectory_sp"), | |
| "concept_verse_edge_bt": build_concept_verse_edge_bt, | |
| "concept_trajectory_bt": build_concept_trajectory_bt, | |
| "concept_verse_edge_pseu": build_concept_verse_edge_pseu, | |
| "concept_trajectory_pseu": build_concept_trajectory_pseu, | |
| "concept_drift": build_concept_drift, | |
| "concept_drift_itp": build_concept_drift_pseu, | |
| "concept_drift_hamilton": build_concept_drift_hamilton, | |
| "community_candidate": lambda: import_community_config("community_candidate"), | |
| "community_membership": lambda: import_community_config("community_membership"), | |
| "concept_centroids": build_concept_centroids, | |
| "concept_aliases": build_concept_aliases, | |
| "concept_verse_edge_patr": build_concept_verse_edge_patr, | |
| "concept_verse_edge_philo": build_concept_verse_edge_philo, | |
| "concept_verse_edge_josephus": build_concept_verse_edge_josephus, | |
| "concept_verse_edge_targum": build_concept_verse_edge_targum, | |
| "concept_verse_edge_talmud": build_concept_verse_edge_talmud, | |
| "concept_verse_edge_nhc": build_concept_verse_edge_nhc, | |
| "concept_trajectory_series": build_concept_trajectory_series, | |
| "concept_drift_sequential": build_concept_drift_sequential, | |
| } | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--config", help="Build only this config") | |
| args = parser.parse_args() | |
| configs = {args.config: CONFIGS[args.config]} if args.config else CONFIGS | |
| if args.config and args.config not in CONFIGS: | |
| print(f"Unknown config '{args.config}'. Valid: {list(CONFIGS)}") | |
| raise SystemExit(1) | |
| print(f"Building {len(configs)} concept-analysis config(s) ...") | |
| for name, fn in configs.items(): | |
| fn() | |
| print(f"\nDone. Output in {OUT}") | |
| if __name__ == "__main__": | |
| main() | |