Download code/population/build_population.py from chiron-group/chiron-data: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/chiron-group/chiron-data/resolve/main/code/population/build_population.py
- Command line
-
hf download hf://datasets/chiron-group/chiron-data/code/population/build_population.py
-
curl -L -o build_population.py https://huggingface.co/datasets/chiron-group/chiron-data/resolve/main/code/population/build_population.py
10.4 kB
| #!/usr/bin/env python3 | |
| """Rebuild synthetic populations from archived model answers and fitted parameters. | |
| Inputs: data/raw/population/{studies.jsonl,split.json,semantic_rules.json} and | |
| data/intermediate/population/{model_responses.jsonl,initial_responses.jsonl,fit_parameters.json}. | |
| Outputs: data/intermediate/population/{population.jsonl,statistics.json}. | |
| The default replays accepted parameters without an API call or a new search. | |
| Use --prepare-source [DIRECTORY] to rebuild study definitions and semantic rules | |
| from the source prompt workbook and human aggregate tables. | |
| Use --from-workbooks [PATH] to read original provider workbooks with | |
| raw/population/source_readout.json instead of the derived model_responses.jsonl. | |
| Run fit_population.py separately to obtain alternative fitted parameters. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import copy | |
| import json | |
| import os | |
| from pathlib import Path | |
| import tempfile | |
| os.environ.setdefault("OPENBLAS_NUM_THREADS", "1") | |
| os.environ.setdefault("OMP_NUM_THREADS", "1") | |
| import numpy as np | |
| from _coupling import finalize_study | |
| from _sources import read_model_responses | |
| from _statistics import score_population | |
| from _transform import replay_fit | |
| ROOT = Path(__file__).resolve().parents[2] | |
| RAW = ROOT / "data/raw/population" | |
| INTERMEDIATE = ROOT / "data/intermediate/population" | |
| def read_rows(path): | |
| with Path(path).open(encoding="utf-8") as handle: | |
| return [json.loads(line) for line in handle if line.strip()] | |
| def validate_input(inp): | |
| keys = [q["condition_key"] for q in inp["prompts"]] | |
| if len(set(keys)) != len(keys) or "Chiron" not in inp["sources"]: | |
| raise ValueError("Unique conditions and archived initial answers are required") | |
| for model, values in inp["sources"].items(): | |
| if set(values) != set(keys): | |
| raise ValueError(f"Incomplete source conditions: {inp['study']}/{model}") | |
| for q in inp["prompts"]: | |
| a = np.asarray(values[q["condition_key"]]) | |
| if (a.shape != (q["original_n"], len(q["questions"])) | |
| or not np.issubdtype(a.dtype, np.integer)): | |
| raise ValueError(f"Invalid answer matrix: {q['condition_key']}/{model}") | |
| for j, question in enumerate(q["questions"]): | |
| if not np.all((a[:, j] >= 1) & (a[:, j] <= len(question["options"]))): | |
| raise ValueError(f"Invalid option IDs: {q['condition_key']}/{model}") | |
| def reconstruct(inp, recipe): | |
| validate_input(inp) | |
| ids = replay_fit(inp, recipe["base"]) | |
| moment = recipe["moment"] | |
| if moment["accepted"]: | |
| anchor = {**inp, "sources": {"anchor": ids}} | |
| ids = replay_fit(anchor, {"model": "anchor", "seed": moment["seed"], | |
| "theta": moment["theta"]}) | |
| return ids | |
| def check_statistics(before, after): | |
| if before.keys() != after.keys(): | |
| raise ValueError("Statistic coverage changed during construction") | |
| checked, maximum = 0, 0.0 | |
| for key, old in before.items(): | |
| new = after[key] | |
| if old["status"] != "ok" or new["status"] != "ok": | |
| raise ValueError(f"Statistic failed: {key}: {old.get('error')} / {new.get('error')}") | |
| a, b = old["statistics"], new["statistics"] | |
| if a.keys() != b.keys(): | |
| raise ValueError(f"Statistic fields changed: {key}") | |
| for field, value in a.items(): | |
| other = b[field] | |
| if isinstance(value, (float, int)): | |
| if not np.isfinite(value) or not np.isfinite(other): | |
| raise ValueError(f"Nonfinite statistic: {key}/{field}") | |
| if not np.isclose(value, other, atol=1e-9, rtol=1e-8): | |
| raise ValueError(f"Protected statistic changed: {key}/{field}") | |
| checked += 1 | |
| maximum = max(maximum, abs(value - other)) | |
| elif value != other: | |
| raise ValueError(f"Statistic metadata changed: {key}/{field}") | |
| return {"effects": len(before), "numeric_fields": checked, | |
| "max_absolute_difference": maximum} | |
| def write_output(path, payload, jsonl=False): | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| temporary = None | |
| try: | |
| with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, | |
| prefix="." + path.name, suffix=".tmp", delete=False) as handle: | |
| temporary = Path(handle.name) | |
| if jsonl: | |
| for row in payload: | |
| handle.write(json.dumps(row, ensure_ascii=False, allow_nan=False) + "\n") | |
| else: | |
| json.dump(payload, handle, ensure_ascii=False, indent=2, allow_nan=False) | |
| handle.write("\n") | |
| temporary.replace(path) | |
| finally: | |
| if temporary is not None: | |
| temporary.unlink(missing_ok=True) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--study", help="Build one training study; default: all training studies") | |
| parser.add_argument("--parameters", type=Path, default=INTERMEDIATE / "fit_parameters.json") | |
| parser.add_argument("--output-dir", type=Path, | |
| help="Output directory; required with --study (default for all studies: data/intermediate/population)") | |
| parser.add_argument("--from-workbooks", nargs="?", type=Path, | |
| const=INTERMEDIATE / "model_archive.zip", metavar="PATH", | |
| help="Read source workbooks from a provider directory or ZIP instead of model_responses.jsonl; default: the saved model_archive.zip") | |
| parser.add_argument("--prepare-source", nargs="?", type=Path, | |
| const=RAW / "upstream", metavar="DIRECTORY", | |
| help="Build studies.jsonl, test_studies.jsonl and semantic_rules.json from prompt.xlsx and human tables; default input: data/raw/population/upstream") | |
| args = parser.parse_args() | |
| if args.prepare_source is not None: | |
| if args.study or args.output_dir or args.from_workbooks is not None or args.parameters != INTERMEDIATE / "fit_parameters.json": | |
| parser.error("--prepare-source cannot be combined with population replay options") | |
| from _definitions import prepare_definitions, prepare_semantic_rules | |
| split = json.loads((RAW / "split.json").read_text(encoding="utf-8")) | |
| readout = json.loads((RAW / "source_readout.json").read_text(encoding="utf-8")) | |
| train, test, conditions = prepare_definitions(args.prepare_source, split, readout) | |
| policy = prepare_semantic_rules(train, conditions, readout["semantic_facts"]) | |
| if (len(train), len(test), sum(len(s["prompts"]) for s in train), | |
| sum(len(s["prompts"]) for s in test)) != (63, 15, 247, 45): | |
| raise ValueError("Unexpected selected study/condition counts") | |
| write_output(RAW / "studies.jsonl", train, jsonl=True) | |
| write_output(RAW / "test_studies.jsonl", test, jsonl=True) | |
| write_output(RAW / "semantic_rules.json", policy) | |
| print("Prepared 63 training studies and 15 evaluation studies from source files") | |
| return | |
| if args.study and args.output_dir is None: | |
| parser.error("--study requires --output-dir to protect the complete population") | |
| output = (args.output_dir or INTERMEDIATE).expanduser().resolve() | |
| if output.is_relative_to(ROOT / "data/raw"): | |
| parser.error("--output-dir must not be inside data/raw") | |
| if args.study and output == INTERMEDIATE: | |
| parser.error("--study must use a separate output directory") | |
| studies = {r["study"]: r for r in read_rows(RAW / "studies.jsonl")} | |
| responses = read_model_responses(INTERMEDIATE / "model_responses.jsonl", studies, workbooks=args.from_workbooks) | |
| split = json.loads((RAW / "split.json").read_text()) | |
| parameters = json.loads(args.parameters.read_text()) | |
| policy = json.loads((RAW / "semantic_rules.json").read_text()) | |
| expected = set(split["train_studies"]) | |
| if set(studies) != expected or set(responses) != expected or expected & set(split["test_studies"]): | |
| raise ValueError("Study inputs do not match the frozen training split") | |
| selected = [args.study] if args.study else sorted(expected) | |
| if not set(selected) <= expected or not set(selected) <= set(parameters): | |
| raise ValueError("Requested study or fitted parameters are missing") | |
| destinations = [output / name for name in ("population.jsonl", "statistics.json")] | |
| protected = {args.parameters.resolve(), RAW / "studies.jsonl", RAW / "split.json", | |
| RAW / "semantic_rules.json", INTERMEDIATE / "model_responses.jsonl", | |
| INTERMEDIATE / "initial_responses.jsonl"} | |
| if protected.intersection(destinations): | |
| raise ValueError("Output would overwrite an input") | |
| populations, before_populations, effects, prompts = [], [], [], [] | |
| refinements = 0 | |
| for study in selected: | |
| inp = {**studies[study], "sources": responses[study]} | |
| ids = reconstruct(inp, parameters[study]) | |
| before_populations.extend({**copy.deepcopy(q), "respondents": ids[q["condition_key"]].tolist()} | |
| for q in inp["prompts"]) | |
| populations.extend(finalize_study(inp, ids, parameters[study], policy)) | |
| effects.extend(inp["effects"]) | |
| prompts.extend(inp["prompts"]) | |
| refinements += bool(parameters[study]["moment"]["accepted"]) | |
| before = score_population(effects, prompts, before_populations) | |
| after = score_population(effects, prompts, populations) | |
| invariant = check_statistics(before["effects"], after["effects"]) | |
| counts = {"studies": len(selected), "conditions": len(populations), | |
| "respondents": sum(q["original_n"] for q in populations), | |
| "answer_positions": sum(q["original_n"] * len(q["questions"]) for q in populations), | |
| "accepted_moment_refinements": refinements, | |
| "statistic_invariance": invariant} | |
| if not args.study and (counts["studies"], counts["conditions"], counts["respondents"]) != (63, 247, 23191): | |
| raise ValueError("Unexpected complete population size") | |
| write_output(destinations[0], populations, jsonl=True) | |
| write_output(destinations[1], after) | |
| print(json.dumps(counts, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |