#!/usr/bin/env python3 """Build literature reference relationships and fixed cohort inputs. python code/measurement/build_construct_relationships.py python code/measurement/build_construct_relationships.py --include-pan15 The default builds reference.jsonl, essays.jsonl and ess09.jsonl. PAN15 requires user-supplied prepared source samples and is generated only when requested. No model calls or random sampling are used. """ from __future__ import annotations import argparse from collections import defaultdict import csv import json import math from pathlib import Path import statistics ROOT = Path(__file__).resolve().parents[2] DATA = ROOT / "data/eval/measurement_construct_relationships" PAN15 = ROOT / "data/raw/measurement/human_gold/pan15_author_profiling/samples.jsonl" def read_json(path): with Path(path).open(encoding="utf-8") as handle: return json.load(handle) def read_rows(path): with Path(path).open(encoding="utf-8") as handle: for line in handle: if line.strip(): yield json.loads(line) def write_rows(path, rows): path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False) + "\n") def build_reference(vocab, minimum_count): groups, used = defaultdict(list), set() for row in read_rows(DATA / "sources/literature_correlations.jsonl"): key = row["evidence_id"] if key in used: raise ValueError(f"Duplicate literature entry: {key}") used.add(key) a, b = row["construct_a"], row["construct_b"] if (a == b or vocab.get(a) != row["construct_a_id"] or vocab.get(b) != row["construct_b_id"]): raise ValueError(f"Invalid construct pair: {key}") value = row["coefficient"] if (type(value) not in (int, float) or not math.isfinite(value) or not -1 <= value <= 1 or not row["coefficient_type"]): raise ValueError(f"Invalid literature coefficient: {key}") groups[tuple(sorted((vocab[a], vocab[b])))].append(row) names = {cid: name for name, cid in vocab.items()} output = [] for (a, b), evidence in sorted(groups.items()): if len(evidence) < minimum_count: continue output.append({ "construct_a_id": a, "construct_a": names[a], "construct_b_id": b, "construct_b": names[b], "correlation": statistics.median(r["coefficient"] for r in evidence), "evidence_count": len(evidence), "evidence_ids": [r["evidence_id"] for r in evidence], }) covered = {r[k] for r in output for k in ("construct_a_id", "construct_b_id")} if (len(used), len(groups), len(output), len(covered)) != (1118, 346, 150, 60): raise ValueError("Expected 1,118 entries, 346 pairs and 150 retained pairs over 60 constructs") return output def sample(sample_id, domain, system, user): return {"sample_id": sample_id, "domain": domain, "messages": [ {"role": "system", "content": system}, {"role": "user", "content": user}, {"role": "assistant", "content": ""}, ]} def record_message(context, records): body = "\n".join(f"- {text.strip()}" for text in records) return f"{context}\n\n{body}\n" def check_groups(groups, key, expected): if len(groups) != expected or len({r[key] for r in groups}) != expected: raise ValueError(f"Expected {expected} unique cohort selections") def build_essays(design): config = design["essays"] path = ROOT / "data/raw/prediction/essays_big5/upstream/essays.csv" with path.open(encoding=config["encoding"], newline="") as handle: source = list(csv.DictReader(handle)) if len(source) != config["source_rows"]: raise ValueError("Unexpected Essays source size") check_groups(config["groups"], "source_row", 2467) output = [] for group in config["groups"]: index = group["source_row"] if type(index) is not int or not 0 <= index < len(source): raise ValueError("Invalid Essays source row") text = source[index]["TEXT"].strip() if not text: raise ValueError("Empty essay") user = config["user_prefix"] + text + config["user_suffix"] output.append(sample(group["sample_id"], "essays_big5", design["system"], user)) return output def build_ess09(design): config = design["ess09"] check_groups(config["groups"], "source_row", 4921) required = {r["source_row"] for r in config["groups"]} path = ROOT / "data/raw/prediction/ess09/upstream/ESS9e03_3.csv" source, count = {}, 0 with path.open(encoding="utf-8-sig", newline="") as handle: for index, row in enumerate(csv.DictReader(handle)): count += 1 if index in required: source[index] = row if count != config["source_rows"] or set(source) != required: raise ValueError("Unexpected ESS09 source size or missing respondents") output = [] for group in config["groups"]: index = group["source_row"] records = [] for variable in group["items"]: item = config["items"][variable] value = source[index][variable] if value not in item["responses"]: raise ValueError(f"Unknown ESS09 response for row {index}, {variable}") records.append(f"Item: {item['text']} | Response: {item['responses'][value]}") if not records: raise ValueError(f"No ESS09 records for row {index}") user = record_message(config["record_context"], records) output.append(sample(f"ess09:{index}", "ess09", design["system"], user)) return output def build_pan15(design, source_path): config = design["pan15"] check_groups(config["groups"], "sample_id", 577) if not source_path.is_file(): raise FileNotFoundError( f"Missing prepared PAN15 samples: {source_path}. See " "data/raw/measurement/human_gold/SOURCE.md and run " "code/measurement/build_human_gold.py --prepare-source --domain pan15_author_profiling." ) required = {r["sample_id"] for r in config["groups"]} source = {} for row in read_rows(source_path): if row.get("domain") != "pan15_author_profiling" or row["sample_id"] not in required: continue key = row["sample_id"] if key in source or row.get("split") != "test": raise ValueError(f"Duplicate or non-test PAN15 sample: {key}") source[key] = row if set(source) != required: raise ValueError(f"Missing {len(required - source.keys())} PAN15 source samples") output = [] for group in config["groups"]: key = group["sample_id"] observations = source[key]["observations"] indices = group["record_indices"] if (not indices or len(indices) != len(set(indices)) or any(type(i) is not int or not 0 <= i < len(observations) for i in indices)): raise ValueError(f"Invalid PAN15 record selection: {key}") user = record_message(config["record_context"], [observations[i] for i in indices]) output.append(sample(f"pan15:{key}", "pan15_author_profiling", design["system"], user)) return output def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output-dir", type=Path, default=DATA) parser.add_argument("--include-pan15", action="store_true") parser.add_argument("--pan15-source", type=Path, default=PAN15) args = parser.parse_args() design = read_json(DATA / "sources/design.json") vocab = read_json(ROOT / "data/raw/measurement/construct_vocab.json") if len(vocab) != 109 or sorted(vocab.values()) != list(range(109)): raise ValueError("Expected the shared 109-construct vocabulary") outputs = { "reference.jsonl": build_reference(vocab, design["minimum_evidence_count"]), "essays.jsonl": build_essays(design), "ess09.jsonl": build_ess09(design), } if args.include_pan15: outputs["pan15.jsonl"] = build_pan15(design, args.pan15_source) for name, rows in outputs.items(): write_rows(args.output_dir / name, rows) print(f"{name}: {len(rows)} rows") if __name__ == "__main__": main()